SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
Bugfix/chat long conversation lag (#269)
Salman Ahamed2e1239148020
diff --git a/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts b/packages/app/src/react/features/ai-chat/clients/chat-api.client.tsindex 96b80882..82832a96 100644--- a/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts+++ b/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts@@ -11,7 +11,7 @@ import {IStreamChunk,IStreamConfig,} from '@react/features/ai-chat/types/chat.types';-import { performanceMonitor } from '@react/features/ai-chat/utils/performance-monitor';+import { performanceMonitor } from '@react/features/ai-chat/utils/chat-performance-monitor';import {createThinkingManager,extractFunctionName,diff --git a/packages/app/src/react/features/ai-chat/components/chat-bubble.tsx b/packages/app/src/react/features/ai-chat/components/chat-bubble.tsxdeleted file mode 100644index 67a0d554..00000000--- a/packages/app/src/react/features/ai-chat/components/chat-bubble.tsx+++ /dev/null@@ -1,364 +0,0 @@-/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */--import '../styles/index.css';--import {- CodeBlock,- FileItemPreview,- ReplyLoader,- ThinkingMessage,-} from '@react/features/ai-chat/components';-import { IChatMessage, IMessageFile } from '@react/features/ai-chat/types/chat.types';-import { Tooltip } from 'flowbite-react';-import { FC, useCallback, useRef, useState } from 'react';-import { FaCheck, FaRegCopy } from 'react-icons/fa6';-import ReactMarkdown from 'react-markdown';-import remarkGfm from 'remark-gfm';--const DEFAULT_AVATAR_URL =- 'https://gravatar.com/avatar/ccd5b19e810febbfd3d4321e27b15f77?s=400&d=mp&r=x';--// Re-export the interface for use in other components-export type { IChatMessage };--/**- * Chat Bubble Component- * Renders different message types based on type discriminator- *- * @param props - IChatMessage properties- * @returns Appropriate message bubble component- */-export const ChatBubble: FC<IChatMessage> = ({- files,- avatar,- message,- type,- onRetryClick,- thinkingMessage,-}) => {- // ✅ Type-based discrimination - type is single source of truth-- // User message- if (type === 'user') {- return <UserMessageBubble message={message} files={files} />;- }-- // Thinking message- if (type === 'thinking') {- return <ThinkingMessage message={message} avatar={avatar} />;- }-- // Loading state (replying/retrying)- if (type === 'loading') {- return <ReplyLoader />;- }-- // Error message- if (type === 'error') {- return (- <SystemMessageBubble- avatar={avatar}- message={message}- isError={true}- onRetryClick={onRetryClick}- isRetrying={false}- thinkingMessage={thinkingMessage}- />- );- }-- // System message (default)- return (- <SystemMessageBubble- avatar={avatar}- message={message}- isError={false}- onRetryClick={onRetryClick}- isRetrying={false}- thinkingMessage={thinkingMessage}- />- );-};--/**- * User Message Bubble Properties- */-interface IUserMessageBubble {- message: string;- files?: IMessageFile[];-}--/**- * User Message Bubble Component- * Displays user's message with optional file attachments- * Message bubble automatically hidden if message is empty- */-const UserMessageBubble: FC<IUserMessageBubble> = ({ message, files }) => {- const hasFiles = files && files.length > 0;-- return (- <div className="break-all flex flex-col items-end">- {/* File Attachments */}- {hasFiles && (- <div className="flex flex-nowrap gap-2 mb-2 overflow-x-auto">- {files.map((fileWithKey, index) => (- <FileItemPreview- isReadOnly- key={fileWithKey.id || index}- file={fileWithKey}- fileKey={fileWithKey.metadata.key}- inChatBubble={true}- />- ))}- </div>- )}-- {/* Message Bubble - automatically hidden if empty */}- {message && (- <div className="rounded-[18px] bg-[#f4f4f4] text-[#2b2b2b] p-3 px-4 w-fit whitespace-pre-wrap text-wrap max-w-[535px]">- {message}- </div>- )}- </div>- );-};--/**- * System Message Bubble Properties- */-interface ISystemMessageBubble {- message: string;- avatar?: string;- isError?: boolean;- isRetrying?: boolean;- onRetryClick?: () => void;- thinkingMessage?: string;-}--/**- * Copy timeout duration (milliseconds)- */-const COPY_RESET_TIMEOUT = 2000;--/**- * Markdown component overrides for consistent formatting- */-const MARKDOWN_COMPONENTS = {- // Headings with proper font sizes- h1: ({ node, ...props }: { node?: unknown }) => (- <h1 style={{ fontWeight: 'bold', fontSize: '2em' }} {...props} />- ),- h2: ({ node, ...props }: { node?: unknown }) => (- <h2 style={{ fontWeight: 'bold', fontSize: '1.5em' }} {...props} />- ),- h3: ({ node, ...props }: { node?: unknown }) => (- <h3 style={{ fontWeight: 'bold', fontSize: '1.17em' }} {...props} />- ),- h4: ({ node, ...props }: { node?: unknown }) => (- <h4 style={{ fontWeight: 'bold', fontSize: '1em' }} {...props} />- ),- h5: ({ node, ...props }: { node?: unknown }) => (- <h5 style={{ fontWeight: 'bold', fontSize: '0.83em' }} {...props} />- ),- h6: ({ node, ...props }: { node?: unknown }) => (- <h6 style={{ fontWeight: 'bold', fontSize: '0.67em' }} {...props} />- ),-- // Code blocks with syntax highlighting- code({- node,- className,- children,- ...props- }: {- node?: unknown;- className?: string;- children?: React.ReactNode;- }) {- const match = /language-(\w+)/.exec(className || '');- return match ? (- <CodeBlock language={match[1]}>{String(children).replace(/\n$/, '')}</CodeBlock>- ) : (- <code className={className} {...props}>- {children}- </code>- );- },-- // Images with responsive styling- img: ({ node, ...props }: { node?: unknown }) => (- <img {...props} className="rounded-xl" style={{ maxWidth: '100%', height: 'auto' }} />- ),-- // Links that open in new tab- a: ({ node, ...props }: { node?: unknown }) => (- <a {...props} target="_blank" rel="noopener noreferrer" />- ),-- // Paragraphs with whitespace preserved- p: ({ children }: { children?: React.ReactNode }) => (- <p className="whitespace-pre-wrap">{children}</p>- ),-};--/**- * System Message Bubble Component- * Displays AI/system response with markdown support and copy functionality- */-const SystemMessageBubble: FC<ISystemMessageBubble> = ({- avatar,- message,- isError,- isRetrying,- onRetryClick,- thinkingMessage,-}) => {- const [copied, setCopied] = useState(false);- const contentRef = useRef<HTMLDivElement>(null);-- /**- * Handles copying message content to clipboard- */- const handleCopy = useCallback(() => {- const content = contentRef.current;- if (!content) return;-- const range = document.createRange();- range.selectNodeContents(content);-- const selection = window.getSelection();- if (!selection) return;-- selection.removeAllRanges();- selection.addRange(range);-- try {- document.execCommand('copy');- setCopied(true);- setTimeout(() => setCopied(false), COPY_RESET_TIMEOUT);- } catch (error) {- console.error('Failed to copy text:', error); // eslint-disable-line no-console- } finally {- selection.removeAllRanges();- }- }, []);-- return (- <div className="system-message-bubble relative">- <div className="flex-1" ref={contentRef}>- {isError ? (- <ErrorMessageBubble- message={message}- onRetryClick={onRetryClick}- isRetrying={isRetrying}- />- ) : (- <div className="chat-rich-text-response space-y-1 rounded-lg p-3 text-[#141414]">- {/* Markdown content with syntax highlighting and formatting */}- <ReactMarkdown- children={message}- remarkPlugins={[remarkGfm]}- components={MARKDOWN_COMPONENTS}- />-- {/* Inline thinking message indicator */}- {thinkingMessage && <ThinkingMessage message={thinkingMessage} avatar={avatar} />}- </div>- )}- </div>- {!isError && !thinkingMessage && (- <div className="flex gap-4 p-4 pl-0">- <Tooltip content={copied ? 'Copied!' : 'Copy'} placement="bottom">- <button- onClick={handleCopy}- className="text-gray-500 hover:text-gray-700 transition-colors"- >- {copied ? <FaCheck /> : <FaRegCopy />}- </button>- </Tooltip>- </div>- )}- </div>- );-};--const ErrorMessageBubble: FC<{- message: string;- onRetryClick: () => void;- isRetrying?: boolean;-}> = ({ message, onRetryClick, isRetrying }) => {- // Check if this is a 401 API key error-- const isApiKeyError =- message.includes('Incorrect API key provided') ||- (message.includes('401') &&- message.toLowerCase().includes('api') &&- message.toLocaleLowerCase().includes('key'));-- return (- <div className="flex flex-col items-start">- <div className="rounded-lg bg-pink-50 border border-pink-200 p-4 max-w-screen-md flex justify-between items-center gap-5">- <div className="flex items-start gap-3">- <div className="flex-shrink-0 mt-0.5">- <svg- width="20"- height="20"- viewBox="0 0 20 20"- fill="currentColor"- xmlns="http://www.w3.org/2000/svg"- className="text-red-500"- >- <path d="M10 9.25C10.4142 9.25002 10.75 9.5858 10.75 10V13.333C10.75 13.7472 10.4142 14.083 10 14.083C9.58579 14.083 9.25 13.7472 9.25 13.333V10C9.25 9.58579 9.58579 9.25 10 9.25Z"></path>- <path d="M10 5.83301C10.5293 5.83303 10.958 6.26273 10.958 6.79199C10.9578 7.3211 10.5291 7.74998 10 7.75C9.47084 7.75 9.04217 7.32111 9.04199 6.79199C9.04199 6.26272 9.47073 5.83301 10 5.83301Z"></path>- <path- fillRule="evenodd"- clipRule="evenodd"- d="M10 2.08496C14.3713 2.08496 17.915 5.62867 17.915 10C17.915 14.3713 14.3713 17.915 10 17.915C5.62867 17.915 2.08496 14.3713 2.08496 10C2.08496 5.62867 5.62867 2.08496 10 2.08496ZM10 3.41504C6.3632 3.41504 3.41504 6.3632 3.41504 10C3.41504 13.6368 6.3632 16.585 10 16.585C13.6368 16.585 16.585 13.6368 16.585 10C16.585 6.3632 13.6368 3.41504 10 3.41504Z"- ></path>- </svg>- </div>-- <div className="flex-1 text-red-700 text-sm leading-relaxed">- {isApiKeyError && (- <>- <h6 className="font-bold">Invalid API Key</h6>- <p>- The API key you provided is not valid. Please set a valid key to continue: - <a- href="/vault"- target="_blank"- className="text-red-700 hover:text-red-900 font-semibold"- >- Set API Key- </a>- </p>- <h6 className="font-semibold pt-1">Error details:</h6>- </>- )}- <ReactMarkdown remarkPlugins={[remarkGfm]}>{message}</ReactMarkdown>- </div>- </div>- {onRetryClick && !isRetrying && (- <button- disabled={isRetrying}- onClick={onRetryClick}- className="inline-flex items-center px-4 gap-x-1 py-2 border border-gray-300 text-sm font-medium rounded-[18px] text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-sm"- >- <svg- width="20"- height="20"- viewBox="0 0 20 20"- fill="currentColor"- xmlns="http://www.w3.org/2000/svg"- aria-label=""- className="-ms-0.5 icon"- >- <path d="M16.4183 9.99967C16.4181 6.45518 13.5448 3.58188 10.0003 3.58171C7.96895 3.58171 6.15935 4.52712 4.98273 6.00163H7.50031L7.6341 6.0153C7.93707 6.07735 8.16535 6.34535 8.16535 6.66667C8.16535 6.98799 7.93707 7.25598 7.6341 7.31803L7.50031 7.33171H3.75031C3.73055 7.33171 3.71104 7.32656 3.69172 7.32487C3.68913 7.32464 3.68649 7.32513 3.68391 7.32487C3.64304 7.32082 3.60409 7.31254 3.56574 7.30143C3.56188 7.30031 3.55788 7.2997 3.55402 7.2985C3.51366 7.286 3.47546 7.27023 3.43879 7.25065L3.43586 7.24967C3.43444 7.24891 3.43337 7.24752 3.43195 7.24675C3.35757 7.20587 3.29219 7.15262 3.23859 7.08757C3.23505 7.08329 3.23128 7.07923 3.22785 7.07487C3.20549 7.04631 3.1858 7.01609 3.16828 6.98405C3.16491 6.97791 3.16169 6.97173 3.15852 6.9655C3.14408 6.93698 3.13265 6.90732 3.12238 6.87663C3.11744 6.86205 3.11264 6.84757 3.10871 6.83268C3.10316 6.81117 3.09843 6.78955 3.09504 6.76725C3.09108 6.74233 3.08833 6.71738 3.08723 6.69206C3.08691 6.68361 3.08527 6.67519 3.08527 6.66667V2.91667C3.08527 2.5494 3.38304 2.25163 3.75031 2.25163C4.11743 2.2518 4.41535 2.54951 4.41535 2.91667V4.62956C5.82462 3.16447 7.80565 2.25163 10.0003 2.25163C14.2793 2.2518 17.7482 5.72065 17.7484 9.99967C17.7484 14.2789 14.2794 17.7485 10.0003 17.7487C6.02899 17.7487 2.75629 14.7612 2.305 10.9108L2.96516 10.8337L3.62531 10.7555C3.99895 13.9437 6.7115 16.4186 10.0003 16.4186C13.5449 16.4184 16.4183 13.5443 16.4183 9.99967ZM2.88801 10.1725C3.25252 10.13 3.58237 10.3911 3.62531 10.7555L2.305 10.9108C2.26225 10.546 2.52323 10.2153 2.88801 10.1725Z"></path>- </svg>- {isRetrying ? 'Retrying...' : 'Retry'}- </button>- )}- </div>- </div>- );-};diff --git a/packages/app/src/react/features/ai-chat/components/chats.tsx b/packages/app/src/react/features/ai-chat/components/chats.tsxindex 83e6038c..559ad9f2 100644--- a/packages/app/src/react/features/ai-chat/components/chats.tsx+++ b/packages/app/src/react/features/ai-chat/components/chats.tsx@@ -16,6 +16,7 @@ interface IChatsProps {containerRef: RefObject<HTMLElement>; // Container ref for scroll controlsmartScrollToBottom: (smooth?: boolean) => void; // Smart scroll to bottom functionhandleFileDrop: (droppedFiles: File[]) => Promise<void>; // File drop handler for drag-and-drop uploads+ shouldAutoScroll: boolean; // Whether auto-scroll is enabled (user is near bottom)}/**@@ -40,32 +41,116 @@ const combineRefs =*/export const Chats: FC<IChatsProps> = (props) => {const { agent, messages, containerRef, handleFileDrop, ...scroll } = props;- const { handleScroll, smartScrollToBottom } = scroll;+ const { handleScroll, smartScrollToBottom, shouldAutoScroll } = scroll;const ref = useRef<HTMLDivElement>(null);const { retryLastMessage } = useChatContext();const dropzoneRef = useDragAndDrop({ onDrop: handleFileDrop });/**- * Auto-scroll effect optimized for streaming- * Only scrolls when last message is system type and changes- * Uses ref to track last scroll to prevent excessive scrolling+ * ULTRA-SMOOTH SCROLL OPTIMIZATION WITH USER CONTROL+ *+ * KEY IMPROVEMENTS:+ * - Instant scroll during streaming (no smooth animation lag)+ * - Aggressive 16ms throttle (60fps) for buttery smoothness+ * - Respects user scroll position (shouldAutoScroll check)+ * - User scrolls up >200px = auto-scroll disabled+ * - User scrolls back to bottom = auto-scroll re-enabled+ * - Uses requestAnimationFrame for perfect frame sync*/const lastScrolledIdRef = useRef<string | number | undefined>();+ const lastMessageLengthRef = useRef<number>(0);+ const lastScrollTimeRef = useRef<number>(0);+ const rafRef = useRef<number | null>(null);+ const { isGenerating } = useChatContext();useEffect(() => {const lastMessage = messages[messages.length - 1];if (!lastMessage) return;- // ✅ Use type-based discrimination instead of 'me' booleanconst isSystemMessage = lastMessage.type === 'system';- // Only scroll if it's a system message and we haven't scrolled for this message yet- if (isSystemMessage && lastMessage.id !== lastScrolledIdRef.current) {- lastScrolledIdRef.current = lastMessage.id;- smartScrollToBottom();+ if (isSystemMessage) {+ const messageLength = lastMessage.message?.length || 0;+ const isNewMessage = lastMessage.id !== lastScrolledIdRef.current;+ const contentGrew = messageLength > lastMessageLengthRef.current;++ if (isNewMessage || contentGrew) {+ lastScrolledIdRef.current = lastMessage.id;+ lastMessageLengthRef.current = messageLength;++ /**+ * ULTRA-SMOOTH SCROLL STRATEGY WITH USER CONTROL:+ *+ * 1. Check shouldAutoScroll FIRST+ * - If user scrolled up >200px, shouldAutoScroll = false+ * - Don't scroll if user is reading history+ * - Result: User stays in control+ *+ * 2. During streaming: Use instant scrolling (no smooth animation)+ * - Reason: Smooth animation causes lag with rapid updates+ * - Result: Instant, responsive, no lag+ *+ * 3. Throttle at 16ms (60fps): Perfect for human perception+ * - Reason: 60fps is maximum visible smoothness+ * - Result: Buttery smooth, no excessive calls+ *+ * 4. Use RAF for frame-perfect timing+ * - Reason: Syncs with browser paint cycle+ * - Result: Smooth, no jank+ */++ // CRITICAL: Check if user wants auto-scroll+ // If user scrolled up >200px, shouldAutoScroll = false+ // This respects user's intent to read history+ if (!shouldAutoScroll) {+ return; // Don't scroll if user is reading above+ }++ const now = performance.now();+ const timeSinceLastScroll = now - lastScrollTimeRef.current;+ const shouldThrottle = !isNewMessage && timeSinceLastScroll < 16; // 60fps++ // Cancel pending RAF+ if (rafRef.current !== null) {+ cancelAnimationFrame(rafRef.current);+ rafRef.current = null;+ }++ const performScroll = () => {+ lastScrollTimeRef.current = performance.now();++ // CRITICAL: Use instant scroll during streaming for smoothness+ // Smooth animation causes lag when content updates rapidly+ if (containerRef?.current) {+ containerRef.current.scrollTo({+ top: containerRef.current.scrollHeight,+ behavior: isGenerating ? 'auto' : 'smooth', // instant during streaming!+ });+ }+ };++ if (shouldThrottle) {+ // Throttle: Use RAF for next frame+ rafRef.current = requestAnimationFrame(() => {+ performScroll();+ rafRef.current = null;+ });+ } else {+ // Immediate: New message or throttle passed+ performScroll();+ }+ }}- }, [messages, smartScrollToBottom]);++ // Cleanup+ return () => {+ if (rafRef.current !== null) {+ cancelAnimationFrame(rafRef.current);+ rafRef.current = null;+ }+ };+ }, [messages, isGenerating, containerRef, shouldAutoScroll]);const avatar = agent?.aiAgentSettings?.avatar;diff --git a/packages/app/src/react/features/ai-chat/components/container.tsx b/packages/app/src/react/features/ai-chat/components/container.tsxindex e0562040..a94dee11 100644--- a/packages/app/src/react/features/ai-chat/components/container.tsx+++ b/packages/app/src/react/features/ai-chat/components/container.tsx@@ -1,14 +1,8 @@import { FC, ReactNode, useCallback, useEffect, useRef } from 'react';-interface ContainerProps {- children: ReactNode;-}--/**- * Container component that overrides parent max-width constraint- * to provide full-width layout for chat interface- */-export const Container: FC<ContainerProps> = ({ children }) => {+type Props = { children: ReactNode };++export const Container: FC<Props> = ({ children }) => {const parentElementRef = useRef<HTMLElement | null>(null);const originalStateRef = useRef<{ className: string; maxWidth: string } | null>(null);diff --git a/packages/app/src/react/features/ai-chat/components/file-item-preview.tsx b/packages/app/src/react/features/ai-chat/components/file-item-preview.tsxindex 836c295c..44d61560 100644--- a/packages/app/src/react/features/ai-chat/components/file-item-preview.tsx+++ b/packages/app/src/react/features/ai-chat/components/file-item-preview.tsx@@ -18,8 +18,7 @@ interface FileItemPreviewProps {isUploading?: boolean;fileKey?: string;isReadOnly?: boolean;- /** Indicates if the preview is being rendered inside a chat bubble */- inChatBubble?: boolean;+ inChatBubble?: boolean; // Indicates if the preview is being rendered inside a chat bubble}const commonProps = { className: 'text-white', fontSize: 20 };diff --git a/packages/app/src/react/features/ai-chat/components/footer.tsx b/packages/app/src/react/features/ai-chat/components/footer.tsxindex 5cf4e064..f8615f84 100644--- a/packages/app/src/react/features/ai-chat/components/footer.tsx+++ b/packages/app/src/react/features/ai-chat/components/footer.tsx@@ -3,7 +3,6 @@ import {ChatInputRef,ErrorToast,ScrollToBottomButton,- WarningInfo,} from '@react/features/ai-chat/components';import { FC, RefObject } from 'react';@@ -30,13 +29,14 @@ export const Footer: FC<FooterProps> = (props) => {} = props;return (- <div className="w-full max-w-4xl">+ <div className="w-full max-w-4xl pt-2.5">{uploadError.show && <ErrorToast message={uploadError.message} onClose={clearError} />}<div className="relative">{showScrollButton && <ScrollToBottomButton onClick={() => scrollToBottom(true)} />}<ChatInput ref={chatInputRef} submitDisabled={submitDisabled} /></div>- <WarningInfo infoMessage={CHAT_WARNING_INFO} />++ <h6 className="py-4 text-center text-xs text-gray-500">{CHAT_WARNING_INFO}</h6></div>);};diff --git a/packages/app/src/react/features/ai-chat/components/index.ts b/packages/app/src/react/features/ai-chat/components/index.tsindex c38cd979..ed398285 100644--- a/packages/app/src/react/features/ai-chat/components/index.ts+++ b/packages/app/src/react/features/ai-chat/components/index.ts@@ -19,4 +19,3 @@ export * from './system-message';export * from './thinking-message';export * from './typewriter';export * from './user-message';-export * from './warning-info';diff --git a/packages/app/src/react/features/ai-chat/components/message-turn-group.tsx b/packages/app/src/react/features/ai-chat/components/message-turn-group.tsxindex 5f8e9c54..654d963f 100644--- a/packages/app/src/react/features/ai-chat/components/message-turn-group.tsx+++ b/packages/app/src/react/features/ai-chat/components/message-turn-group.tsx@@ -14,13 +14,9 @@ import { IChatMessage } from '../types/chat.types';import { Chat } from './chat';interface IMessageTurnGroupProps {- /** Messages in this conversation turn (all share same conversationTurnId) */- messages: IChatMessage[];- /** Agent avatar URL */- avatar?: string;- /** Retry callback for error messages */- onRetryClick?: () => void;- /** Scroll to bottom callback */+ messages: IChatMessage[]; // Messages in this conversation turn (all share same conversationTurnId)+ avatar?: string; // Agent avatar URL+ onRetryClick?: () => void; // Retry callback for error messagesscrollToBottom: (smooth?: boolean) => void; // eslint-disable-line no-unused-vars}diff --git a/packages/app/src/react/features/ai-chat/components/system-message.tsx b/packages/app/src/react/features/ai-chat/components/system-message.tsxindex 82cb434a..8b03f6c5 100644--- a/packages/app/src/react/features/ai-chat/components/system-message.tsx+++ b/packages/app/src/react/features/ai-chat/components/system-message.tsx@@ -46,7 +46,6 @@ export const SystemMessage: FC<ISystemMessageProps> = (props) => {{typingAnimation ? (<Typewritermessage={message}- speed={2}isTyping={typingAnimation}onComplete={onTypingComplete}onTypingProgress={onTypingProgress}diff --git a/packages/app/src/react/features/ai-chat/components/thinking-message.tsx b/packages/app/src/react/features/ai-chat/components/thinking-message.tsxindex 94762d17..be388b0d 100644--- a/packages/app/src/react/features/ai-chat/components/thinking-message.tsx+++ b/packages/app/src/react/features/ai-chat/components/thinking-message.tsx@@ -28,7 +28,7 @@ const ThinkingMessage: React.FC<ThinkingMessageProps> = ({ message, avatar }) =><div className="flex items-center gap-3">{/* Avatar inside the bubble */}<div className="flex-shrink-0">- <div className="w-6 h-6 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden">+ <div className="size-6 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden">{avatar ? (<img src={avatar} alt="AI Avatar" className="w-full h-full object-cover" />) : (diff --git a/packages/app/src/react/features/ai-chat/components/typewriter.tsx b/packages/app/src/react/features/ai-chat/components/typewriter.tsxindex 7f7a2069..b86ddd75 100644--- a/packages/app/src/react/features/ai-chat/components/typewriter.tsx+++ b/packages/app/src/react/features/ai-chat/components/typewriter.tsx@@ -1,12 +1,10 @@-import { FC, useCallback, useEffect, useState } from 'react';+import { FC, useEffect, useState } from 'react';import { MarkdownRenderer } from '@react/features/ai-chat/components';-import { forceScrollToBottom } from '@react/features/ai-chat/utils/scroll-utils';import { useChatContext } from '../contexts';interface ITypewriterProps {message: string;- speed?: number;onComplete?: () => void;isTyping?: boolean;minSpeed?: number;@@ -20,7 +18,6 @@ interface ITypewriterProps {*/export const Typewriter: FC<ITypewriterProps> = ({message,- speed = 5,onComplete,isTyping = true,minSpeed = 1,@@ -32,43 +29,16 @@ export const Typewriter: FC<ITypewriterProps> = ({const [lastMessageLength, setLastMessageLength] = useState(0);const { isGenerating = true } = useChatContext();- // Fast typewriter-effect library style speed- const getTypingSpeed = useCallback((char: string, messageLength: number): number => {- // Very fast base speed like typewriter-effect library- let baseSpeed = 20; // 20ms base speed (very fast)-- // Character-specific speeds (minimal variation for smoothness)- if (char === ' ' || char === '\n') {- baseSpeed = 10; // Almost instant for spaces- } else if (/[a-zA-Z0-9]/.test(char)) {- baseSpeed = 15; // Very fast for letters/numbers- } else if (/[.,!?;:]/.test(char)) {- baseSpeed = 25; // Slight pause for punctuation- } else if (/[{}()[\]<>]/.test(char)) {- baseSpeed = 12; // Fast for brackets- } else if (char === '\t') {- baseSpeed = 8; // Very fast for tabs- } else if (/[#*`~]/.test(char)) {- baseSpeed = 18; // Fast for markdown- }-- // Add tiny random variation for natural feel (like typewriter-effect)- const variation = (Math.random() - 0.5) * 8; // ±4ms variation- baseSpeed += variation;-- // Slightly faster for longer messages (like typewriter-effect)- if (messageLength > 200) {- baseSpeed *= 0.8;- }- if (messageLength > 500) {- baseSpeed *= 0.7;- }- if (messageLength > 1000) {- baseSpeed *= 0.6;- }-- return Math.max(5, baseSpeed); // Minimum 5ms for ultra-smoothness- }, []);+ /**+ * PERFORMANCE OPTIMIZATION:+ * Instant streaming display without artificial typing delay+ *+ * Previous issue: 1 character per 1ms = 1000ms for 1000 chars+ * Solution: Instant display as chunks arrive (0ms delay)+ *+ * Result: Real-time streaming like ChatGPT+ */+ const TYPING_SPEED = 0; // Zero delay - truly instant display// Handle immediate display when generation is completeuseEffect(() => {@@ -82,17 +52,19 @@ export const Typewriter: FC<ITypewriterProps> = ({}}, [isGenerating, message, onComplete]);- // Separate effect for force scroll only when generation completes- useEffect(() => {- if (!isGenerating && message.length > 0) {- // Force scroll to bottom when message is fully generated (ignores user scroll position)-- // Add a small delay to ensure the content is fully rendered- setTimeout(() => {- forceScrollToBottom({ behavior: 'smooth', delay: 0 });- }, 200);- }- }, [isGenerating]); // eslint-disable-line react-hooks/exhaustive-deps+ /**+ * SCROLL OPTIMIZATION:+ * Removed duplicate scroll trigger from typewriter+ *+ * Reason: chats.tsx already handles scrolling with smartScrollToBottom+ * Having multiple scroll triggers causes conflicts and inconsistent behavior+ *+ * The main scroll logic in chats.tsx is more intelligent:+ * - Respects user scroll position (shouldAutoScroll)+ * - Tracks message changes properly+ * - Works consistently across all scenarios+ */+ // REMOVED: Duplicate scroll logic (handled by chats.tsx)useEffect(() => {if (!isTyping) {@@ -111,24 +83,16 @@ export const Typewriter: FC<ITypewriterProps> = ({}if (currentIndex < message.length) {- const currentChar = message[currentIndex];- const dynamicSpeed = getTypingSpeed(currentChar, message.length);-- // Fast typewriter-effect style batching for smooth performance- let batchSize = 1;-- // Smart batching based on message length (like typewriter-effect library)- if (message.length > 2000) {- batchSize = currentChar === ' ' || currentChar === '\n' ? 8 : 3;- } else if (message.length > 1000) {- batchSize = currentChar === ' ' || currentChar === '\n' ? 6 : 2;- } else if (message.length > 500) {- batchSize = currentChar === ' ' || currentChar === '\n' ? 4 : 2;- } else if (message.length > 200) {- batchSize = currentChar === ' ' || currentChar === '\n' ? 3 : 1;- } else {- batchSize = currentChar === ' ' || currentChar === '\n' ? 2 : 1;- }+ /**+ * PERFORMANCE OPTIMIZATION:+ * Display entire new content instantly instead of character-by-character+ *+ * Previous: 1 char at a time = 1000 updates for 1000 chars+ * Now: All new content at once = 1 update+ *+ * This gives instant streaming display as chunks arrive from server+ */+ const batchSize = message.length - currentIndex; // Display all remaining content instantlyconst charsToAdd = message.slice(currentIndex, currentIndex + batchSize);@@ -137,7 +101,7 @@ export const Typewriter: FC<ITypewriterProps> = ({setCurrentIndex((prevIndex) => prevIndex + batchSize);// Trigger scroll during typing progressonTypingProgress?.();- }, dynamicSpeed);+ }, TYPING_SPEED);return () => clearTimeout(timer);} else if (currentIndex >= message.length && displayedText.length === message.length) {@@ -145,7 +109,6 @@ export const Typewriter: FC<ITypewriterProps> = ({}}, [message,- speed,currentIndex,displayedText.length,isTyping,@@ -153,7 +116,7 @@ export const Typewriter: FC<ITypewriterProps> = ({onTypingProgress,minSpeed,maxSpeed,- getTypingSpeed,+ TYPING_SPEED,]);// Reset only when message length decreases (new message) or when message is emptydiff --git a/packages/app/src/react/features/ai-chat/components/warning-info.tsx b/packages/app/src/react/features/ai-chat/components/warning-info.tsxdeleted file mode 100644index a6b5b3cb..00000000--- a/packages/app/src/react/features/ai-chat/components/warning-info.tsx+++ /dev/null@@ -1,9 +0,0 @@-import { FC } from 'react';--interface WarningInfoProps {- infoMessage: string;-}--export const WarningInfo: FC<WarningInfoProps> = ({ infoMessage }) => (- <h6 className="py-4 text-center text-xs text-gray-500">{infoMessage}</h6>-);diff --git a/packages/app/src/react/features/ai-chat/hooks/index.ts b/packages/app/src/react/features/ai-chat/hooks/index.tsindex 0917d92a..cd6ecd0e 100644--- a/packages/app/src/react/features/ai-chat/hooks/index.ts+++ b/packages/app/src/react/features/ai-chat/hooks/index.ts@@ -1,12 +1,8 @@export * from './agent-settings';export * from './use-agent-chat-context';export * from './use-chat';-export * from './use-chat-actions';-export * from './use-chat-state';export * from './use-chat-stream';-export * from './use-chatbot-state';export * from './use-create-chat';export * from './use-drag-and-drop';export * from './use-fileupload';-export * from './use-scroll-behavior';export * from './use-scroll-to-bottom';diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.tsdeleted file mode 100644index 4a9cf464..00000000--- a/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts+++ /dev/null@@ -1,437 +0,0 @@-import { useCallback, useRef, useState } from 'react';--import { CHAT_ERROR_MESSAGE } from '@react/features/ai-chat/constants';-import { chatUtils } from '@react/features/ai-chat/utils';-import { FileWithMetadata, IChatMessage } from '@react/shared/types/chat.types';--interface UseChatActionsProps {- agentId: string;- chatId: string;- avatar?: string;- onChatComplete?: () => void;-}--interface UseChatActionsReturn {- messagesHistory: IChatMessage[];- isGenerating: boolean;- isInputProcessing: boolean;- isRetrying: boolean;- sendMessage: (message: string, attachedFiles?: FileWithMetadata[]) => Promise<void>; // eslint-disable-line no-unused-vars- retryLastMessage: () => void;- stopGenerating: () => void;- clearMessages: () => void;-}--// Interface to store last user message with files-interface LastUserMessage {- message: string;- attachedFiles?: FileWithMetadata[];-}--export const useChatActions = ({- agentId,- chatId,- avatar,- onChatComplete,-}: UseChatActionsProps): UseChatActionsReturn => {- const [messagesHistory, setMessagesHistory] = useState<IChatMessage[]>([]);- const [isGenerating, setIsGenerating] = useState(false);- const [isInputProcessing, setIsInputProcessing] = useState(false);- const [isRetrying, setIsRetrying] = useState(false);-- // Store both message and attached files for retry functionality- const lastUserMessageRef = useRef<LastUserMessage>({ message: '', attachedFiles: [] });- const abortControllerRef = useRef<AbortController | null>(null);-- const clearMessages = useCallback(() => {- setMessagesHistory([]);- lastUserMessageRef.current = { message: '', attachedFiles: [] };- }, []);-- const stopGenerating = useCallback(() => {- if (abortControllerRef.current) {- abortControllerRef.current.abort();- abortControllerRef.current = null;- }- setIsGenerating(false);- setIsInputProcessing(false);- }, []);-- const sendMessage = useCallback(- async (message: string, attachedFiles?: FileWithMetadata[]) => {- if (!message.trim() && (!attachedFiles || attachedFiles.length === 0)) return;-- // Store the complete message with files for retry functionality- lastUserMessageRef.current = {- message,- attachedFiles: attachedFiles || [],- };-- // Add user message to chat history- if (message.trim()) {- setMessagesHistory((prev) => {- const newMessage: IChatMessage = {- me: true,- message: message.replace(/\n/g, '\n'),- type: 'user',- files: attachedFiles,- };- return [...prev, newMessage];- });- } else if (attachedFiles?.length) {- setMessagesHistory((prev) => {- const newMessage: IChatMessage = {- me: true,- message: '',- type: 'user',- files: attachedFiles,- hideMessage: true,- };- return [...prev, newMessage];- });- }-- // Add initial AI response message- const replyMessage: IChatMessage = {- me: false,- message: '',- type: 'system',- avatar,- isReplying: true,- };-- setMessagesHistory((prev) => [...prev, replyMessage]);-- try {- setIsInputProcessing(true);- setIsGenerating(true);-- abortControllerRef.current = new AbortController();- const signal = abortControllerRef.current.signal;-- await chatUtils.generateResponse({- agentId,- query: message,- attachments: (attachedFiles || [])- .map((f) => ({- url: f.metadata.publicUrl,- name: f.file?.name,- type: f.metadata.fileType,- size: f.file?.size,- }))- .filter((a) => !!a.url),- chatId,- signal,- onResponse: (value: string, errorInfo?: { isError?: boolean; errorType?: string }) => {- setMessagesHistory((bubbles) => {- // Only remove thinking messages if we have actual content- if (value && value.trim() !== '') {- const filteredBubbles = bubbles.filter((msg) => msg.type !== 'thinking');-- // Find the last system message- const lastSystemMessageIndex =- filteredBubbles- .map((msg, index) => ({ msg, index }))- .filter(({ msg }) => msg.type === 'system')- .pop()?.index ?? -1;-- if (lastSystemMessageIndex !== -1) {- // Update the system message with final response and error info- const updatedBubbles = [...filteredBubbles];- updatedBubbles[lastSystemMessageIndex].message = value;- updatedBubbles[lastSystemMessageIndex].isReplying = false;- updatedBubbles[lastSystemMessageIndex].isError = errorInfo?.isError || false;- updatedBubbles[lastSystemMessageIndex].hideMessage = false; // Show the message bubble- updatedBubbles[lastSystemMessageIndex].thinkingMessage = undefined; // Clear thinking message- return updatedBubbles;- }- return filteredBubbles;- } else {- // Keep thinking messages if no content yet- return bubbles;- }- });- },- onThinking: (thinking) => {- setMessagesHistory((bubbles) => {- // Find the last system message index- const lastSystemIndex =- bubbles- .map((msg, index) => ({ msg, index }))- .filter(({ msg }) => msg.type === 'system')- .pop()?.index ?? -1;-- if (lastSystemIndex !== -1) {- // Update the existing system message with thinking message instead of creating separate bubble- const updatedBubbles = [...bubbles];- updatedBubbles[lastSystemIndex].thinkingMessage = thinking.message;- updatedBubbles[lastSystemIndex].isReplying = false;- return updatedBubbles;- }-- return bubbles;- });- },- onStart: () => {- setMessagesHistory((prev) => {- const newMessages = [...prev];- const lastMessage = newMessages[newMessages.length - 1];- if (lastMessage && lastMessage.type === 'system') {- // Show initial processing message and loading indicator- lastMessage.message = '';- lastMessage.isReplying = true; // Show loading indicator for system message- }- return newMessages;- });- },- onEnd: () => {- setMessagesHistory((prev) => {- // Remove thinking messages when response is complete- const filteredMessages = prev.filter((msg) => msg.type !== 'thinking');- const newMessages = [...filteredMessages];-- // Clear thinkingMessage from all system messages- newMessages.forEach((msg) => {- if (msg.type === 'system') {- msg.thinkingMessage = undefined;- }- });-- const lastMessage = newMessages[newMessages.length - 1];- if (lastMessage) {- lastMessage.isReplying = false;- }- return newMessages;- });- setIsRetrying(false);- setIsGenerating(false);- onChatComplete?.();- abortControllerRef.current = null;- },- });- } catch (error) {- if (error.name === 'AbortError') {- setMessagesHistory((prev) => {- const newMessages = [...prev];- const lastMessage = newMessages[newMessages.length - 1];- if (lastMessage) {- lastMessage.isReplying = false;- lastMessage.message += '';- }- return newMessages;- });- } else {- setMessagesHistory((prev) => {- const newMessages = [...prev];- const lastMessage = newMessages[newMessages.length - 1];- if (lastMessage) {- lastMessage.isReplying = false;- lastMessage.message = CHAT_ERROR_MESSAGE;- lastMessage.isError = true;- }- return newMessages;- });- }- } finally {- setIsInputProcessing(false);- setIsRetrying(false);- setIsGenerating(false);- }- },- [agentId, chatId, avatar, onChatComplete],- );-- const retryLastMessage = useCallback(() => {- const lastMessage = lastUserMessageRef.current;- if (- lastMessage.message ||- (lastMessage.attachedFiles && lastMessage.attachedFiles.length > 0)- ) {- // Remove the last error message and replace it with a new AI response message- setMessagesHistory((prev) => {- const newMessages = [...prev];- const lastMessageIndex = newMessages.length - 1;-- if (lastMessageIndex >= 0 && newMessages[lastMessageIndex].isError) {- // Replace the error message with a new AI response message- newMessages[lastMessageIndex] = {- me: false,- message: '',- type: 'system',- avatar,- isReplying: true,- isError: false,- };- }-- return newMessages;- });-- // Retry the API call without adding a new user message- const retryApiCall = async () => {- try {- setIsInputProcessing(true);- setIsGenerating(true);-- abortControllerRef.current = new AbortController();- const signal = abortControllerRef.current.signal;-- await chatUtils.generateResponse({- agentId,- query: lastMessage.message,- attachments: (lastUserMessageRef.current.attachedFiles || [])- .map((f) => ({- url: f.metadata.publicUrl,- name: f.file?.name,- type: f.metadata.fileType,- size: f.file?.size,- }))- .filter((a) => !!a.url),- chatId,- signal,- onResponse: (value: string, errorInfo?: { isError?: boolean; errorType?: string }) => {- setMessagesHistory((bubbles) => {- // Only remove thinking messages if we have actual content- if (value && value.trim() !== '') {- const filteredBubbles = bubbles.filter((msg) => msg.type !== 'thinking');-- // Find the last system message- const lastSystemMessageIndex =- filteredBubbles- .map((msg, index) => ({ msg, index }))- .filter(({ msg }) => msg.type === 'system')- .pop()?.index ?? -1;-- if (lastSystemMessageIndex !== -1) {- // Update the system message with final response and error info- const updatedBubbles = [...filteredBubbles];- updatedBubbles[lastSystemMessageIndex].message = value;- updatedBubbles[lastSystemMessageIndex].isReplying = false;- updatedBubbles[lastSystemMessageIndex].isError = errorInfo?.isError || false;- updatedBubbles[lastSystemMessageIndex].hideMessage = false;- return updatedBubbles;- }- return filteredBubbles;- } else {- // Keep thinking messages if no content yet- return bubbles;- }- });- },- onThinking: (thinking) => {- setMessagesHistory((bubbles) => {- // Find the last system message index- const lastSystemIndex =- bubbles- .map((msg, index) => ({ msg, index }))- .filter(({ msg }) => msg.type === 'system')- .pop()?.index ?? -1;-- // Check if there's already a thinking message after the last system message- const thinkingAfterSystem = bubbles- .slice(lastSystemIndex + 1)- .find((msg) => msg.type === 'thinking');-- if (thinkingAfterSystem) {- // Update existing thinking message- thinkingAfterSystem.message = thinking.message;- return [...bubbles];- } else {- // Add new thinking message after the last system message- const thinkingMessage: IChatMessage = {- me: false,- message: thinking.message,- type: 'thinking',- avatar,- isReplying: false,- };-- const newBubbles = [...bubbles];- if (lastSystemIndex !== -1) {- // Insert after the last system message- newBubbles.splice(lastSystemIndex + 1, 0, thinkingMessage);- // Hide the system message when thinking starts- newBubbles[lastSystemIndex].hideMessage = true;- newBubbles[lastSystemIndex].isReplying = false;- } else {- // Add at the end if no system message- newBubbles.push(thinkingMessage);- }-- return newBubbles;- }- });- },- onStart: () => {- setMessagesHistory((prev) => {- const newMessages = [...prev];- const lastMessage = newMessages[newMessages.length - 1];- if (lastMessage && lastMessage.type === 'system') {- lastMessage.isReplying = true;- }- return newMessages;- });- },- onEnd: () => {- setMessagesHistory((prev) => {- // Remove thinking messages when response is complete- const filteredMessages = prev.filter((msg) => msg.type !== 'thinking');- const newMessages = [...filteredMessages];- const lastMessage = newMessages[newMessages.length - 1];- if (lastMessage) {- lastMessage.isReplying = false;- }- return newMessages;- });- setIsRetrying(false);- setIsGenerating(false);- onChatComplete?.();- abortControllerRef.current = null;- },- });- } catch (error) {- if (error.name === 'AbortError') {- setMessagesHistory((prev) => {- const newMessages = [...prev];- const lastMessage = newMessages[newMessages.length - 1];- if (lastMessage) {- lastMessage.isReplying = false;- lastMessage.message += '';- }- return newMessages;- });- } else {- setMessagesHistory((prev) => {- const newMessages = [...prev];- const lastMessage = newMessages[newMessages.length - 1];- if (lastMessage) {- lastMessage.isReplying = false;- lastMessage.message = error.error || error.message || CHAT_ERROR_MESSAGE;- lastMessage.isError = true;- }- return newMessages;- });- }- } finally {- setIsInputProcessing(false);- setIsRetrying(false);- setIsGenerating(false);- }- };-- retryApiCall();- setIsRetrying(false);- }- }, [agentId, chatId, avatar, onChatComplete]);-- return {- messagesHistory,- isGenerating,- isInputProcessing,- isRetrying,- sendMessage,- retryLastMessage,- stopGenerating,- clearMessages,- };-};diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-state.tsdeleted file mode 100644index ebd3a79a..00000000--- a/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts+++ /dev/null@@ -1,148 +0,0 @@-import { useCallback, useRef, useState } from 'react';--interface ChatStateProps {- agentId?: string;- domain?: string;- devPort?: number | null;- apiHeaders?: Record<string, string>;-}--interface ChatMessage {- id: number;- type: 'system' | 'user' | 'debug';- content: string;- attachments?: any[];- updatedAt: number;- isTyped?: boolean;-}--interface DefaultMessage {- id: number;- type: 'system';- content: string;- isTyped: boolean;-}--/**- * Custom hook for chat state management (inspired by ChatBox functionality)- * Manages chat messages, user input, AI responses, and chat interactions- */-export const useChatState = ({ agentId, domain, devPort, apiHeaders }: ChatStateProps) => {- const [messages, setMessages] = useState<ChatMessage[]>([]);- const [debugInfo, setDebugInfo] = useState<any[]>([]);- const [userInput, setUserInput] = useState('');- const [isLoading, setIsLoading] = useState(false);- const [errorMessage, setErrorMessage] = useState('');- const [executedIndices, setExecutedIndices] = useState<number[]>([]);- const [isFunctionCall, setIsFunctionCall] = useState(false);- const [hasUserScrolled, setHasUserScrolled] = useState(false);- const [canSendNewMessage, setCanSendNewMessage] = useState(true);- const [defaultMessage, setDefaultMessage] = useState<DefaultMessage>({- id: 1,- type: 'system',- content: '',- isTyped: false,- });- const [isGenerating, setIsGenerating] = useState(false);- const [userStoppedGeneration, setUserStoppedGeneration] = useState(false);- const abortControllerRef = useRef<AbortController | null>(null);-- /**- * Handles user input submission and AI response generation- * @param isRetry - Whether this is a retry attempt- * @param attachments - File attachments to include with the message- */- const handleUserInputSubmit = useCallback(- async (isRetry: boolean, attachments: any[] = []): Promise<void> => {- if (!userInput.trim() && attachments.length === 0) return;-- try {- setIsGenerating(true);- setErrorMessage('');- setCanSendNewMessage(false);-- // Create user message- const userMessage: ChatMessage = {- id: Date.now(),- type: 'user',- content: userInput,- attachments,- updatedAt: Date.now(),- };-- setMessages((prev) => [...prev, userMessage]);- setUserInput('');-- // Simulate AI response- setTimeout(() => {- const aiMessage: ChatMessage = {- id: Date.now() + 1,- type: 'system',- content: `I received your message: "${userInput}". This is a simulated response from the AI assistant.`,- updatedAt: Date.now() + 1,- };-- setMessages((prev) => [...prev, aiMessage]);- setIsGenerating(false);- setCanSendNewMessage(true);- }, 2000);- } catch (error) {- console.error('Error sending message:', error);- setErrorMessage('Failed to send message. Please try again.');- setIsGenerating(false);- setCanSendNewMessage(true);- }- },- [userInput],- );-- /**- * Stops the current AI generation process- */- const handleStopGenerating = useCallback((): void => {- if (abortControllerRef.current) {- abortControllerRef.current.abort();- }- setIsGenerating(false);- setUserStoppedGeneration(true);- setCanSendNewMessage(true);- }, []);-- /**- * Handles JSON objects from AI responses (for debug info)- * @param jsonObjects - Array of JSON objects to process- */- const handleJSONObjects = useCallback((jsonObjects: any[]): void => {- setDebugInfo(jsonObjects);- }, []);-- return {- messages,- setMessages,- debugInfo,- setDebugInfo,- userInput,- setUserInput,- isLoading,- setIsLoading,- errorMessage,- setErrorMessage,- executedIndices,- setExecutedIndices,- isFunctionCall,- setIsFunctionCall,- hasUserScrolled,- setHasUserScrolled,- canSendNewMessage,- setCanSendNewMessage,- defaultMessage,- setDefaultMessage,- isGenerating,- setIsGenerating,- userStoppedGeneration,- setUserStoppedGeneration,- handleUserInputSubmit,- handleStopGenerating,- handleJSONObjects,- };-};diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat.tsindex 04c39369..8fcb3449 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-chat.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat.ts@@ -287,7 +287,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {pendingUpdateRef.current = null;}updateThrottleRef.current = null;- }, 50); // 50ms throttle - balances performance and responsiveness+ }, 16); // 16ms throttle (60fps) - ultra-smooth, matches scroll rate}, []);/**diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chatbot-state.ts b/packages/app/src/react/features/ai-chat/hooks/use-chatbot-state.tsdeleted file mode 100644index dbb53ce5..00000000--- a/packages/app/src/react/features/ai-chat/hooks/use-chatbot-state.ts+++ /dev/null@@ -1,158 +0,0 @@-import { useCallback, useState } from 'react';--interface ChatbotStateProps {- isBoxOpen?: boolean;- isChatOnly?: boolean;- domain?: string;- props?: any;-}--interface ChatbotSettings {- domain?: string;- chatbotEnabled: boolean;- name: string;- introMessage: string;- port: number;- headers: Record<string, string>;- authRequired: boolean;- colors: {- chatTogglerColors: {- backgroundColor: string;- textColor: string;- };- chatWindowColors: {- backgroundColor: string;- };- botBubbleColors: {- backgroundColorStart: string;- backgroundColorEnd: string;- textColor: string;- };- };- botBubbleClass: string;- humanBubbleClass: string;- syntaxHighlightTheme: string;-}--/**- * Custom hook for chatbot state management (inspired by ChatBox functionality)- * Manages chatbot configuration, settings, authentication, and UI state- */-export const useChatbotState = ({ isBoxOpen, isChatOnly, domain, props }: ChatbotStateProps) => {- const [isTyped, setIsTyped] = useState(false);- const [currentMessage, setCurrentMessage] = useState('');- const [devPort, setDevPort] = useState<number | null>(null);- const [isOpen, setIsOpen] = useState(isBoxOpen || isChatOnly);- const [isOpenStyle, setIsOpenStyle] = useState(false);- const [defaultSettings, setDefaultSettings] = useState<ChatbotSettings>({- chatbotEnabled: true,- name: 'AI Assistant',- introMessage: 'Hi, I am your AI assistant. How can I help you?',- port: 3000,- headers: {},- authRequired: false,- colors: {- chatTogglerColors: {- backgroundColor: '#45c98d',- textColor: '#ffffff',- },- chatWindowColors: {- backgroundColor: '#ffffff',- },- botBubbleColors: {- backgroundColorStart: '#f3f4f6',- backgroundColorEnd: '#e5e7eb',- textColor: '#374151',- },- },- botBubbleClass: '',- humanBubbleClass: '',- syntaxHighlightTheme: 'prism',- ...props,- });- const [isDefaultSettingsLoading, setIsDefaultSettingsLoading] = useState(false);- const [isAuthVerificationLoading, setIsAuthVerificationLoading] = useState(false);- const [apiHeaders, setApiHeaders] = useState<Record<string, string>>();-- /**- * Loads chatbot settings from API or configuration- * In real implementation, this would fetch from API- */- const loadSettings = useCallback(async (): Promise<ChatbotSettings> => {- try {- setIsDefaultSettingsLoading(true);- // Mock settings loading - in real implementation, this would fetch from API- const settings: ChatbotSettings = {- domain,- chatbotEnabled: true,- name: 'AI Assistant',- introMessage: 'Hi, I am your AI assistant. How can I help you?',- port: 3000,- headers: {},- authRequired: false,- colors: {- chatTogglerColors: {- backgroundColor: '#45c98d',- textColor: '#ffffff',- },- chatWindowColors: {- backgroundColor: '#ffffff',- },- botBubbleColors: {- backgroundColorStart: '#f3f4f6',- backgroundColorEnd: '#e5e7eb',- textColor: '#374151',- },- },- botBubbleClass: '',- humanBubbleClass: '',- syntaxHighlightTheme: 'prism',- ...props,- };-- setDefaultSettings(settings);- setDevPort(settings.port);- setApiHeaders(settings.headers);-- return settings;- } catch (error) {- console.error('Error loading settings:', error);- throw error;- } finally {- setIsDefaultSettingsLoading(false);- }- }, [domain, props]);-- /**- * Verifies authentication if required- */- const verifyAuth = useCallback(async (): Promise<void> => {- if (!defaultSettings?.authRequired) return;-- try {- setIsAuthVerificationLoading(true);- await loadSettings();- } catch (error) {- console.error('Auth verification failed:', error);- } finally {- setIsAuthVerificationLoading(false);- }- }, [defaultSettings?.authRequired, loadSettings]);-- return {- devPort,- isOpen,- setIsOpen,- setIsTyped,- apiHeaders,- verifyAuth,- isOpenStyle,- loadSettings,- setIsOpenStyle,- defaultSettings,- setCurrentMessage,- setDefaultSettings,- isDefaultSettingsLoading,- isAuthVerificationLoading,- };-};diff --git a/packages/app/src/react/features/ai-chat/hooks/use-drag-and-drop.ts b/packages/app/src/react/features/ai-chat/hooks/use-drag-and-drop.tsindex c526facf..f2ad8e17 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-drag-and-drop.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-drag-and-drop.ts@@ -1,7 +1,7 @@-import { useEffect, useRef, useCallback, RefObject } from 'react';+import { RefObject, useCallback, useEffect, useRef } from 'react';interface UseDragAndDropProps {- onDrop: (files: File[]) => Promise<void>;+ onDrop: (files: File[]) => Promise<void>; // eslint-disable-line no-unused-vars}/**diff --git a/packages/app/src/react/features/ai-chat/hooks/use-scroll-behavior.ts b/packages/app/src/react/features/ai-chat/hooks/use-scroll-behavior.tsdeleted file mode 100644index 9b2b8435..00000000--- a/packages/app/src/react/features/ai-chat/hooks/use-scroll-behavior.ts+++ /dev/null@@ -1,76 +0,0 @@-import { useCallback, useEffect, useRef } from 'react';--/**- * Custom hook for scroll behavior (inspired by ChatBox functionality)- * Manages chat scroll behavior, auto-scroll, and user scroll detection- * @param messages - Array of chat messages- * @param hasUserScrolled - Whether user has manually scrolled- * @param setHasUserScrolled - Function to set user scroll state- */-export const useScrollBehavior = (- messages: any[],- hasUserScrolled: boolean,- setHasUserScrolled: (value: boolean) => void,-) => {- const chatBoxRef = useRef<HTMLDivElement>(null);- const chatEndRef = useRef<HTMLDivElement>(null);-- /**- * Scrolls to the bottom of the chat with smooth animation- */- const scrollToBottom = useCallback((): void => {- if (chatEndRef.current) {- chatEndRef.current.scrollIntoView({ behavior: 'smooth' });- }- }, []);-- /**- * Handles scroll events to detect user scrolling- */- const handleScroll = useCallback(- (event: Event): void => {- const target = event.target as HTMLElement;- if (!target) return;-- const { scrollTop, scrollHeight, clientHeight } = target;- const isAtBottom = scrollHeight - scrollTop - clientHeight < 10;-- if (!isAtBottom && !hasUserScrolled) {- setHasUserScrolled(true);- } else if (isAtBottom && hasUserScrolled) {- setHasUserScrolled(false);- }- },- [hasUserScrolled, setHasUserScrolled],- );-- /**- * Auto-scroll to bottom when new messages arrive (if user hasn't scrolled up)- */- useEffect(() => {- if (!hasUserScrolled) {- scrollToBottom();- }- }, [messages, hasUserScrolled, scrollToBottom]);-- /**- * Add scroll event listener to chat container- */- useEffect(() => {- const chatContainer = chatBoxRef.current;- if (!chatContainer) return;-- chatContainer.addEventListener('scroll', handleScroll);-- return () => {- chatContainer.removeEventListener('scroll', handleScroll);- };- }, [handleScroll]);-- return {- chatBoxRef,- chatEndRef,- scrollToBottom,- handleScroll,- };-};diff --git a/packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.ts b/packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.tsindex 8d5dc6f9..420d8b3d 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.ts@@ -19,11 +19,25 @@ export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {if (ref.current) {const { scrollTop, scrollHeight, clientHeight } = ref.current;- const isScrolledUp = scrollHeight - scrollTop > clientHeight + 100; // 100px threshold++ /**+ * ULTRA-AGGRESSIVE THRESHOLD: Maximum scroll retention+ *+ * Problem: Even 150px was too strict for smooth streaming+ *+ * Solution: 200px threshold + Math.ceil for most lenient behavior+ * - User must scroll up >200px to disable auto-scroll+ * - Small scroll movements don't break tracking+ * - Perfect for streaming and long chats+ */+ const distanceFromBottom = Math.ceil(scrollHeight - scrollTop - clientHeight);+ const threshold = 200; // Ultra-forgiving threshold++ const isScrolledUp = distanceFromBottom > threshold;setShowScrollButton(isScrolledUp);// Update auto-scroll state based on scroll position- const isNearBottom = scrollHeight - scrollTop <= clientHeight + 100;+ const isNearBottom = distanceFromBottom <= threshold;setShouldAutoScroll(isNearBottom);}}, [ref]);@@ -42,15 +56,22 @@ export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {[ref],);- // Professional smart scroll function+ /**+ * CRITICAL FIX: Don't block scrolling based on shouldAutoScroll+ *+ * Previous issue: if (!shouldAutoScroll) return; blocked ALL scrolling+ * This caused streaming to lose scroll tracking in long conversations+ *+ * New approach: Pass shouldAutoScroll to scroll manager, let IT decide+ * This allows context-aware scrolling (streaming vs not streaming)+ */const smartScrollToBottom = useCallback((smooth: boolean = true) => {- if (!shouldAutoScroll) return;-- // Use professional scroll manager+ // Don't check shouldAutoScroll here - let scroll manager handle it+ // This is critical for streaming behaviorscrollManager.smartScrollToBottom({ behavior: smooth ? 'smooth' : 'auto', delay: 0 });},- [shouldAutoScroll],+ [], // Removed shouldAutoScroll dependency - scroll manager handles it internally);useEffect(() => {diff --git a/packages/app/src/react/features/ai-chat/pages/agent-chat.tsx b/packages/app/src/react/features/ai-chat/pages/agent-chat.tsxdeleted file mode 100644index 356f2128..00000000--- a/packages/app/src/react/features/ai-chat/pages/agent-chat.tsx+++ /dev/null@@ -1,105 +0,0 @@-import { useEffect, useRef } from 'react';-import { useParams } from 'react-router-dom';--import {- ChatHeader,- ChatInputRef,- Chats,- Container,- Footer,-} from '@react/features/ai-chat/components';-import { ChatProvider } from '@react/features/ai-chat/contexts';-import { useAgentChatContext, useScrollToBottom } from '@react/features/ai-chat/hooks';--/**- * Agent Chat Page Component- * Modern implementation using new chat hooks with professional architecture- *- * This component is a thin wrapper that:- * 1. Extracts route params- * 2. Sets up chat context via useAgentChatContext hook- * 3. Manages UI refs (input, container)- * 4. Handles scroll behavior- * 5. Renders chat UI components- */-const AgentChatPage = () => {- const params = useParams<{ agentId: string }>();- const agentId = params?.agentId;-- // UI refs for input focus and scroll management- const chatInputRef = useRef<ChatInputRef>(null);- const chatContainerRef = useRef<HTMLDivElement>(null);-- // ============================================================================- // CHAT CONTEXT SETUP- // ============================================================================- // All chat logic is now encapsulated in this single hook- const {- chatContextValue,- agent,- agentSettings,- isLoading,- sharedMessagesHistory,- handleFileDrop,- } = useAgentChatContext({- agentId: agentId || '',- onChatReady: () => chatInputRef.current?.focus(), // Focus input when chat is ready- onChatCleared: () => chatInputRef.current?.focus(), // Focus input after clearing chat- });-- // ============================================================================- // SCROLL BEHAVIOR- // ============================================================================- const { smartScrollToBottom, scrollToBottom, showScrollButton, ...scroll } =- useScrollToBottom(chatContainerRef);-- // ============================================================================- // UI EFFECTS- // ============================================================================-- /**- * Auto-focus input when agent is loaded and not disabled- */- useEffect(() => {- if (!isLoading.agent && !chatContextValue.inputDisabled) chatInputRef.current?.focus();- }, [isLoading.agent, chatContextValue.inputDisabled]);-- // ============================================================================- // RENDER- // ============================================================================-- return (- <ChatProvider value={chatContextValue}>- <Container>- <ChatHeader- agentName={agent?.name}- avatar={agentSettings?.settings?.avatar}- isAgentLoading={isLoading.agent}- isAvatarLoading={isLoading.settings}- />-- <Chats- {...scroll}- agent={agent}- messages={sharedMessagesHistory}- containerRef={chatContainerRef}- handleFileDrop={handleFileDrop}- smartScrollToBottom={smartScrollToBottom}- />-- <Footer- chatInputRef={chatInputRef}- clearError={chatContextValue.clearError}- uploadError={chatContextValue.uploadError}- scrollToBottom={scrollToBottom}- showScrollButton={showScrollButton}- submitDisabled={- isLoading.chatCreating || isLoading.agent || chatContextValue.uploadingFiles.size > 0- }- />- </Container>- </ChatProvider>- );-};--export default AgentChatPage;diff --git a/packages/app/src/react/features/ai-chat/pages/ai-chat.old.tsx b/packages/app/src/react/features/ai-chat/pages/ai-chat.old.tsxdeleted file mode 100644index 3f2035c4..00000000--- a/packages/app/src/react/features/ai-chat/pages/ai-chat.old.tsx+++ /dev/null@@ -1,205 +0,0 @@-import { useCallback, useEffect, useRef } from 'react';-import { useNavigate, useParams } from 'react-router-dom';--import {- ChatHeader,- ChatInputRef,- Chats,- Container,- Footer,-} from '@react/features/ai-chat/components';-import { ChatProvider } from '@react/features/ai-chat/contexts';-import {- useAgentSettings,- useChatActions,- useCreateChatMutation,- useFileUpload,- useScrollToBottom,- useUpdateAgentSettingsMutation,-} from '@react/features/ai-chat/hooks';-import { FILE_LIMITS } from '@react/features/ai-chat/utils/file';-import { useAgent } from '@react/shared/hooks/agent';-import { Observability } from '@shared/observability';-import { EVENTS } from '@shared/posthog/constants/events';--const AIChat = () => {- const params = useParams<{ agentId: string }>();- const agentId = params?.agentId;- const chatInputRef = useRef<ChatInputRef>(null);- const chatContainerRef = useRef<HTMLDivElement>(null);- const isFirstMessageSentRef = useRef(false);- const hasInitializedChatRef = useRef(false);- const navigate = useNavigate();-- // API Hooks - optimized with minimal dependencies- const { data: agent, isLoading: isAgentLoading } = useAgent(agentId || '', {- refetchOnWindowFocus: false,- refetchOnReconnect: false,- retry: false,- onError: () => navigate('/error/403'),- });-- const { data: settingsData, isLoading: isAgentSettingsLoading } = useAgentSettings(agentId || '');- const { mutateAsync: createChat, isPending: isChatCreating } = useCreateChatMutation();- const { mutateAsync: updateAgentSettings } = useUpdateAgentSettingsMutation();-- const agentSettings = settingsData?.settings;-- // Custom Hooks - optimized- const { setShowScrollButton, smartScrollToBottom, scrollToBottom, showScrollButton, ...scroll } =- useScrollToBottom(chatContainerRef);-- const {- files,- uploadingFiles,- uploadError,- handleFileChange,- handleFileDrop,- removeFile,- clearError,- isUploadInProgress,- clearFiles,- } = useFileUpload({- agentId: agentId || '',- chatId: agentSettings?.lastConversationId,- });-- const {- messagesHistory,- isGenerating,- isInputProcessing,- isRetrying,- sendMessage,- retryLastMessage,- stopGenerating,- clearMessages,- } = useChatActions({- agentId: agentId || '',- chatId: agentSettings?.lastConversationId,- avatar: agent?.aiAgentSettings?.avatar,- onChatComplete: () => {- if (!isFirstMessageSentRef.current) {- isFirstMessageSentRef.current = true;- }- },- });-- // Fast memoized values - minimal dependencies- const inputDisabled = isChatCreating || isAgentLoading || isInputProcessing;- const queryInputPlaceholder = agent ? `Message ${agent?.name}...` : 'Message ...';- const isMaxFilesUploaded = files.length >= FILE_LIMITS.MAX_ATTACHED_FILES;-- // Fast callbacks - minimal dependencies- const createNewChatSession = useCallback(async () => {- try {- const conversation = await createChat({- conversation: {- summary: '',- chunkSize: 100,- lastChunkID: '0',- label: 'New Chat',- aiAgentId: agentId || '',- },- });-- await updateAgentSettings({- agentId: agentId || '',- settings: { key: 'lastConversationId', value: conversation?.id },- });- } catch (error) {- console.error('Error creating chat session', error); // eslint-disable-line no-console- }- }, [agentId, createChat, updateAgentSettings]);-- const clearChatSession = useCallback(async () => {- stopGenerating();- setShowScrollButton(false);- isFirstMessageSentRef.current = false;- clearMessages();- await createNewChatSession();- chatInputRef.current?.focus();- Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);- Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);- }, [createNewChatSession, clearMessages, stopGenerating, setShowScrollButton]);-- useEffect(() => {- if (agentSettings && agent && !hasInitializedChatRef.current) {- agent.aiAgentSettings = agentSettings;- agent.id = agentId;-- // This ensures fresh conversation every time user loads the page- hasInitializedChatRef.current = true;- createNewChatSession();- }- }, [agentSettings, agent, agentId, createNewChatSession]);-- useEffect(() => {- if (!isAgentLoading && !inputDisabled) chatInputRef.current?.focus();- }, [isAgentLoading, inputDisabled]);-- useEffect(() => {- Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);- return () => Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);- }, []);-- // Fast context value - minimal dependencies- const chatContextValue = {- // File handling- files,- uploadingFiles,- isUploadInProgress,- isMaxFilesUploaded,- handleFileChange,- handleFileDrop,- removeFile,- clearFiles,- uploadError,- clearError,-- // Chat state- isGenerating,- isInputProcessing,- isRetrying,- messagesHistory,- inputPlaceholder: queryInputPlaceholder,- inputDisabled,-- // Chat actions- sendMessage,- retryLastMessage,- stopGenerating,- clearChatSession,- };-- return (- <ChatProvider value={chatContextValue}>- <Container>- <ChatHeader- agentName={agent?.name}- avatar={agentSettings?.avatar}- isAgentLoading={isAgentLoading}- isAvatarLoading={isAgentSettingsLoading}- />-- <Chats- {...scroll}- agent={agent}- messages={messagesHistory}- containerRef={chatContainerRef}- handleFileDrop={handleFileDrop}- smartScrollToBottom={smartScrollToBottom}- />- <Footer- chatInputRef={chatInputRef}- clearError={clearError}- uploadError={uploadError}- scrollToBottom={scrollToBottom}- showScrollButton={showScrollButton}- submitDisabled={isChatCreating || isAgentLoading || uploadingFiles.size > 0}- />- </Container>- </ChatProvider>- );-};--export default AIChat;diff --git a/packages/app/src/react/features/ai-chat/utils/performance-monitor.ts b/packages/app/src/react/features/ai-chat/utils/chat-performance-monitor.tssimilarity index 54%rename from packages/app/src/react/features/ai-chat/utils/performance-monitor.tsrename to packages/app/src/react/features/ai-chat/utils/chat-performance-monitor.tsindex 52b4af6e..4ab9b127 100644--- a/packages/app/src/react/features/ai-chat/utils/performance-monitor.ts+++ b/packages/app/src/react/features/ai-chat/utils/chat-performance-monitor.ts@@ -1,37 +1,82 @@+/* eslint-disable no-console *//*** Performance Monitoring Utility for Chat Streaming*- * Helps identify bottlenecks in:+ * PRODUCTION-SAFE monitoring tool that helps identify bottlenecks in:* - Network latency (server response time)* - Chunk processing time* - UI render time*+ * Features:+ * - Zero performance impact when disabled+ * - Automatic memory cleanup+ * - Type-safe implementation+ * - ESLint compliant+ ** Usage:* 1. Enable via localStorage: localStorage.setItem('CHAT_DEBUG_MODE', 'true')* 2. Check console for detailed metrics- * 3. Use getMetrics() to analyze performance+ * 3. Use window.chatDebug.metrics() to analyze performance+ *+ * @example+ * // Enable monitoring+ * window.chatDebug.enable();+ *+ * // After chat stream completes+ * const metrics = window.chatDebug.metrics();+ * console.log(metrics);*/+/**+ * Represents a single chunk's performance metrics+ */interface ChunkMetric {- timestamp: number;- chunkIndex: number;- networkTime?: number; // Time from request to chunk arrival- processingTime?: number; // Time to process chunk- renderTime?: number; // Time to render in UI- chunkSize: number; // Size in bytes- type: 'content' | 'thinking' | 'tool' | 'debug';+ timestamp: number; // High-resolution timestamp when chunk was received+ chunkIndex: number; // Sequential index of this chunk in the stream+ networkTime?: number; // Time elapsed since previous chunk (milliseconds)+ processingTime?: number; // Time spent processing/parsing the chunk (milliseconds)+ renderTime?: number; // Time spent rendering the chunk in UI (milliseconds)+ chunkSize: number; // Size of chunk data in bytes+ type: 'content' | 'thinking' | 'tool' | 'debug'; // Type of content in this chunk}+/**+ * Aggregated performance metrics for an entire stream+ */interface PerformanceMetrics {- totalChunks: number;- averageNetworkTime: number;- averageProcessingTime: number;- averageRenderTime: number;- totalDuration: number;- slowestChunk: ChunkMetric | null;- chunksPerSecond: number;+ totalChunks: number; // Total number of chunks received+ averageNetworkTime: number; // Average time between chunks (milliseconds)+ averageProcessingTime: number; // Average processing time per chunk (milliseconds)+ averageRenderTime: number; // Average render time per chunk (milliseconds)+ totalDuration: number; // Total stream duration (milliseconds)+ slowestChunk: ChunkMetric | null; // Chunk with highest total latency+ chunksPerSecond: number; // Throughput in chunks per second+}++/**+ * Global debug interface exposed on window object+ */+interface ChatDebugInterface {+ enable: () => void; // Enable performance monitoring+ disable: () => void; // Disable performance monitoring+ metrics: () => PerformanceMetrics; // Get current performance metrics}+/**+ * Extend Window interface with chatDebug property+ */+declare global {+ interface Window {+ chatDebug: ChatDebugInterface;+ }+}++/**+ * Maximum number of chunks to track before cleanup+ * Prevents memory issues in very long sessions+ */+const MAX_METRICS_SIZE = 10000;+class PerformanceMonitor {private enabled: boolean = false;private metrics: ChunkMetric[] = [];@@ -45,6 +90,38 @@ class PerformanceMonitor {typeof window !== 'undefined' && localStorage.getItem('CHAT_DEBUG_MODE') === 'true';}+ /**+ * Safe console logging wrapper+ * Only logs when monitoring is enabled+ */+ private log(...args: unknown[]): void {+ if (this.enabled && typeof console !== 'undefined') console.log(...args);+ }++ /**+ * Safe console warning wrapper+ */+ private warn(...args: unknown[]): void {+ if (this.enabled && typeof console !== 'undefined') console.warn(...args);+ }++ /**+ * Safe console error wrapper+ */+ private error(...args: unknown[]): void {+ if (this.enabled && typeof console !== 'undefined') console.error(...args);+ }++ /**+ * Cleanup old metrics to prevent memory bloat+ */+ private cleanupOldMetrics(): void {+ if (this.metrics.length > MAX_METRICS_SIZE) {+ // Keep only the most recent 1000 metrics+ this.metrics = this.metrics.slice(-1000);+ }+ }+/*** Starts monitoring a new stream*/@@ -56,12 +133,14 @@ class PerformanceMonitor {this.chunkIndex = 0;this.metrics = [];- console.log('%c🚀 STREAM STARTED', 'color: #00ff00; font-weight: bold; font-size: 14px');- console.log(`⏱️ Start Time: ${new Date().toISOString()}`);+ this.log('%c🚀 STREAM STARTED', 'color: #00ff00; font-weight: bold; font-size: 14px');+ this.log(`⏱️ Start Time: ${new Date().toISOString()}`);}/*** Records when a chunk arrives from network+ * @param chunkData - Raw chunk data received+ * @param type - Type of chunk content*/recordChunkArrival(chunkData: string, type: ChunkMetric['type'] = 'content'): void {if (!this.enabled) return;@@ -80,9 +159,12 @@ class PerformanceMonitor {this.metrics.push(metric);this.lastChunkTime = now;+ // Cleanup if metrics array is getting too large+ this.cleanupOldMetrics();+// Log if chunk took too long (> 100ms is suspicious)if (networkTime > 100) {- console.warn(+ this.warn(`⚠️ SLOW CHUNK #${metric.chunkIndex}: ${networkTime.toFixed(2)}ms (${metric.chunkSize} bytes)`,`Type: ${type}`,);@@ -91,6 +173,8 @@ class PerformanceMonitor {/*** Records chunk processing time+ * @param chunkIndex - Index of the chunk being processed+ * @param processingTime - Time taken to process in milliseconds*/recordProcessingTime(chunkIndex: number, processingTime: number): void {if (!this.enabled) return;@@ -100,13 +184,14 @@ class PerformanceMonitor {metric.processingTime = processingTime;if (processingTime > 50) {- console.warn(`⚠️ SLOW PROCESSING #${chunkIndex}: ${processingTime.toFixed(2)}ms`);+ this.warn(`⚠️ SLOW PROCESSING #${chunkIndex}: ${processingTime.toFixed(2)}ms`);}}}/*** Records UI render time+ * @param renderTime - Time taken to render in milliseconds*/recordRenderTime(renderTime: number): void {if (!this.enabled) return;@@ -117,7 +202,7 @@ class PerformanceMonitor {if (renderTime > 16.67) {// More than 1 frame at 60fps- console.warn(+ this.warn(`⚠️ SLOW RENDER #${lastMetric.chunkIndex}: ${renderTime.toFixed(2)}ms (dropped frames!)`,);}@@ -126,6 +211,7 @@ class PerformanceMonitor {/*** Ends stream and shows summary+ * Displays comprehensive performance report in console*/endStream(): void {if (!this.enabled) return;@@ -133,22 +219,22 @@ class PerformanceMonitor {const totalDuration = performance.now() - this.streamStartTime;const metrics = this.getMetrics();- console.log('%c✅ STREAM COMPLETED', 'color: #00ff00; font-weight: bold; font-size: 14px');- console.log(`⏱️ Total Duration: ${totalDuration.toFixed(2)}ms`);- console.log(`📦 Total Chunks: ${metrics.totalChunks}`);- console.log(`⚡ Chunks/Second: ${metrics.chunksPerSecond.toFixed(2)}`);- console.log('\n📊 PERFORMANCE BREAKDOWN:');- console.log(` 🌐 Network (avg): ${metrics.averageNetworkTime.toFixed(2)}ms`);- console.log(` ⚙️ Processing (avg): ${metrics.averageProcessingTime.toFixed(2)}ms`);- console.log(` 🎨 Rendering (avg): ${metrics.averageRenderTime.toFixed(2)}ms`);+ this.log('%c✅ STREAM COMPLETED', 'color: #00ff00; font-weight: bold; font-size: 14px');+ this.log(`⏱️ Total Duration: ${totalDuration.toFixed(2)}ms`);+ this.log(`📦 Total Chunks: ${metrics.totalChunks}`);+ this.log(`⚡ Chunks/Second: ${metrics.chunksPerSecond.toFixed(2)}`);+ this.log('\n📊 PERFORMANCE BREAKDOWN:');+ this.log(` 🌐 Network (avg): ${metrics.averageNetworkTime.toFixed(2)}ms`);+ this.log(` ⚙️ Processing (avg): ${metrics.averageProcessingTime.toFixed(2)}ms`);+ this.log(` 🎨 Rendering (avg): ${metrics.averageRenderTime.toFixed(2)}ms`);if (metrics.slowestChunk) {- console.log('\n🐌 SLOWEST CHUNK:');- console.log(` Index: #${metrics.slowestChunk.chunkIndex}`);- console.log(` Network: ${metrics.slowestChunk.networkTime?.toFixed(2)}ms`);- console.log(` Processing: ${metrics.slowestChunk.processingTime?.toFixed(2)}ms`);- console.log(` Render: ${metrics.slowestChunk.renderTime?.toFixed(2)}ms`);- console.log(` Size: ${metrics.slowestChunk.chunkSize} bytes`);+ this.log('\n🐌 SLOWEST CHUNK:');+ this.log(` Index: #${metrics.slowestChunk.chunkIndex}`);+ this.log(` Network: ${metrics.slowestChunk.networkTime?.toFixed(2)}ms`);+ this.log(` Processing: ${metrics.slowestChunk.processingTime?.toFixed(2)}ms`);+ this.log(` Render: ${metrics.slowestChunk.renderTime?.toFixed(2)}ms`);+ this.log(` Size: ${metrics.slowestChunk.chunkSize} bytes`);}// Identify bottleneck@@ -157,14 +243,15 @@ class PerformanceMonitor {/*** Analyzes metrics and identifies the bottleneck+ * @param metrics - Performance metrics to analyze*/private identifyBottleneck(metrics: PerformanceMetrics): void {const { averageNetworkTime, averageProcessingTime, averageRenderTime } = metrics;- console.log('\n🎯 BOTTLENECK ANALYSIS:');+ this.log('\n🎯 BOTTLENECK ANALYSIS:');if (averageNetworkTime > 50) {- console.error(+ this.error('❌ SERVER/NETWORK BOTTLENECK DETECTED!',`\n Average network time: ${averageNetworkTime.toFixed(2)}ms`,'\n ➡️ Issue: Chunks are arriving slowly from server',@@ -173,7 +260,7 @@ class PerformanceMonitor {}if (averageProcessingTime > 30) {- console.error(+ this.error('❌ CHUNK PROCESSING BOTTLENECK DETECTED!',`\n Average processing time: ${averageProcessingTime.toFixed(2)}ms`,'\n ➡️ Issue: Parsing/processing chunks is slow',@@ -182,7 +269,7 @@ class PerformanceMonitor {}if (averageRenderTime > 16.67) {- console.error(+ this.error('❌ UI RENDERING BOTTLENECK DETECTED!',`\n Average render time: ${averageRenderTime.toFixed(2)}ms`,'\n ➡️ Issue: UI updates are slow (dropping frames)',@@ -191,7 +278,7 @@ class PerformanceMonitor {}if (averageNetworkTime <= 50 && averageProcessingTime <= 30 && averageRenderTime <= 16.67) {- console.log('✅ NO BOTTLENECKS DETECTED! Performance is optimal.');+ this.log('✅ NO BOTTLENECKS DETECTED! Performance is optimal.');}}@@ -252,24 +339,26 @@ class PerformanceMonitor {/*** Enables debug mode+ * Persists setting to localStorage*/enable(): void {this.enabled = true;if (typeof window !== 'undefined') {localStorage.setItem('CHAT_DEBUG_MODE', 'true');}- console.log('✅ Performance monitoring enabled');+ this.log('✅ Performance monitoring enabled');}/*** Disables debug mode+ * Removes setting from localStorage*/disable(): void {this.enabled = false;if (typeof window !== 'undefined') {localStorage.removeItem('CHAT_DEBUG_MODE');}- console.log('❌ Performance monitoring disabled');+ this.log('❌ Performance monitoring disabled');}/**@@ -280,12 +369,23 @@ class PerformanceMonitor {}}-// Singleton instance+/**+ * Singleton instance of PerformanceMonitor+ * Single instance ensures consistent tracking across the application+ */export const performanceMonitor = new PerformanceMonitor();-// Global helpers for browser console+/**+ * Initialize global debug interface for browser console access+ * Safely attaches to window object with proper TypeScript typing+ *+ * Usage in browser console:+ * - window.chatDebug.enable() - Enable monitoring+ * - window.chatDebug.disable() - Disable monitoring+ * - window.chatDebug.metrics() - Get current metrics+ */if (typeof window !== 'undefined') {- (window as any).chatDebug = {+ window.chatDebug = {enable: () => performanceMonitor.enable(),disable: () => performanceMonitor.disable(),metrics: () => performanceMonitor.getMetrics(),diff --git a/packages/app/src/react/features/ai-chat/utils/scroll-utils.ts b/packages/app/src/react/features/ai-chat/utils/scroll-utils.tsindex 16fbf2c3..a6d42703 100644--- a/packages/app/src/react/features/ai-chat/utils/scroll-utils.ts+++ b/packages/app/src/react/features/ai-chat/utils/scroll-utils.ts@@ -66,13 +66,20 @@ export class ScrollManager {/*** Check if user is near bottom of scroll container+ *+ * ULTRA-AGGRESSIVE: Very forgiving threshold for smooth streaming+ * - 200px threshold (was 150px) - more aggressive auto-scroll+ * - Math.ceil for more lenient calculation+ * - Better for long chats and rapid content growth*/- isNearBottom(threshold: number = 100): boolean {+ isNearBottom(threshold: number = 200): boolean {const container = this.getContainer();if (!container) return true;const { scrollTop, scrollHeight, clientHeight } = container;- return scrollHeight - scrollTop <= clientHeight + threshold;+ // Use Math.ceil for more lenient behavior (rounds up distance)+ const distanceFromBottom = Math.ceil(scrollHeight - scrollTop - clientHeight);+ return distanceFromBottom <= threshold;}/**@@ -117,27 +124,43 @@ export class ScrollManager {return;}- // Don't scroll if user is scrolled up and force is false- if (!force && !this.isNearBottom()) {+ /**+ * ULTRA-AGGRESSIVE SCROLL: Maximum responsiveness+ *+ * - force=true: Always scroll (no questions asked)+ * - force=false: Very lenient 200px threshold+ * - Result: User rarely loses scroll tracking+ *+ * Philosophy: During streaming, keeping content visible is+ * more important than respecting small scroll-up movements+ */+ if (!force && !this.isNearBottom(200)) {+ // Ultra-forgiving 200px thresholdresolve();return;}this.isScrolling = true;- // Use modern scrollTo API with smooth behavior+ /**+ * PERFORMANCE: Direct scrollTo for instant response+ * - No animation delay+ * - Maximum responsiveness+ * - Perfect for streaming+ */container.scrollTo({top: container.scrollHeight,behavior: behavior === 'instant' ? 'auto' : behavior,});- // Reset scrolling flag after animation+ // Reset scrolling flagif (behavior === 'smooth') {this.scrollTimeout = window.setTimeout(() => {this.isScrolling = false;resolve();- }, 300); // Typical smooth scroll duration+ }, 300);} else {+ // Instant scroll - no delay neededthis.isScrolling = false;resolve();}