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
Refactor Chat Components for Enhanced State Management and Code Clarity
Salman-Ahamede3a55f42c28d
diff --git a/packages/app/src/react/features/ai-chat/components/chats.tsx b/packages/app/src/react/features/ai-chat/components/chats.tsxindex 9f15bc33..a2b44e2c 100644--- a/packages/app/src/react/features/ai-chat/components/chats.tsx+++ b/packages/app/src/react/features/ai-chat/components/chats.tsx@@ -1,21 +1,8 @@-/* eslint-disable no-unused-vars */import { Chat, ChatsTurnGroup } from '@react/features/ai-chat/components';-import { useChatContext } from '@react/features/ai-chat/contexts';-import { useDragAndDrop } from '@react/features/ai-chat/hooks';+import { useChatStores, useDragAndDrop } from '@react/features/ai-chat/hooks';import { IChatMessage } from '@react/features/ai-chat/types/chat.types';-import { AgentDetails } from '@src/react/shared/types/agent-data.types';import { FC, MutableRefObject, RefObject, useEffect, useMemo, useRef } from 'react';-interface IChatsProps {- agent: AgentDetails;- messages: IChatMessage[];- handleScroll: () => void;- containerRef: RefObject<HTMLElement>;- smartScrollToBottom: (smooth?: boolean) => void;- handleFileDrop: (droppedFiles: File[]) => Promise<void>;- shouldAutoScroll: boolean;-}-/*** Combines multiple refs into a single ref callback* Useful for managing multiple refs on the same element@@ -36,19 +23,26 @@ const combineRefs =* Chats Component* Renders chat messages with smart auto-scroll and drag-and-drop support*/-export const Chats: FC<IChatsProps> = (props) => {- const { agent, messages, containerRef, handleFileDrop, ...scroll } = props;- const { handleScroll, smartScrollToBottom, shouldAutoScroll } = scroll;+export const Chats: FC = () => {+ const { ref: allRefs, agent: agentData, chat, files, scroll } = useChatStores() || {};++ const agent = agentData?.data;+ const containerRef = allRefs?.container;+ const handleFileDrop = files.addFiles;+ const { messages, isStreaming, retryMessage } = chat || {};++ // ============================================================================+ // SCROLL BEHAVIOR+ // ============================================================================+ const { handleScroll, smartScrollToBottom, shouldAutoScroll } = scroll || {};const ref = useRef<HTMLDivElement>(null);- const { retryMessage } = useChatContext();const dropzoneRef = useDragAndDrop({ onDrop: handleFileDrop });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];@@ -82,7 +76,7 @@ export const Chats: FC<IChatsProps> = (props) => {if (containerRef?.current) {containerRef.current.scrollTo({top: containerRef.current.scrollHeight,- behavior: isGenerating ? 'auto' : 'smooth',+ behavior: isStreaming ? 'auto' : 'smooth',});}};@@ -104,7 +98,7 @@ export const Chats: FC<IChatsProps> = (props) => {rafRef.current = null;}};- }, [messages, isGenerating, containerRef, shouldAutoScroll]);+ }, [messages, isStreaming, containerRef, shouldAutoScroll]);const avatar = agent?.aiAgentSettings?.avatar;@@ -178,9 +172,9 @@ export const Chats: FC<IChatsProps> = (props) => {if (group.turnId && group.messages.length > 0) {return (<ChatsTurnGroup+ avatar={avatar}key={group.turnId}messages={group.messages}- avatar={avatar}onRetryClick={onRetryClick}scrollToBottom={smartScrollToBottom}/>@@ -192,8 +186,8 @@ export const Chats: FC<IChatsProps> = (props) => {key={message.id || `${groupIndex}-${messageIndex}`}{...message}avatar={avatar}- onRetryClick={messageIndex === group.messages.length - 1 ? onRetryClick : undefined}scrollToBottom={smartScrollToBottom}+ onRetryClick={messageIndex === group.messages.length - 1 ? onRetryClick : undefined}/>));})}diff --git a/packages/app/src/react/features/ai-chat/components/footer.tsx b/packages/app/src/react/features/ai-chat/components/footer.tsxindex f8615f84..aa896eef 100644--- a/packages/app/src/react/features/ai-chat/components/footer.tsx+++ b/packages/app/src/react/features/ai-chat/components/footer.tsx@@ -1,39 +1,21 @@-import {- ChatInput,- ChatInputRef,- ErrorToast,- ScrollToBottomButton,-} from '@react/features/ai-chat/components';-import { FC, RefObject } from 'react';--interface FooterProps {- uploadError: { show: boolean; message: string };- clearError: () => void;- chatInputRef: RefObject<ChatInputRef>;- submitDisabled: boolean;- showScrollButton: boolean;- scrollToBottom: (smooth?: boolean) => void; // eslint-disable-line no-unused-vars-}+import { ChatInput, ErrorToast, ScrollToBottomButton } from '@react/features/ai-chat/components';+import { useChatStores } from '@react/features/ai-chat/hooks';+import { FC } from 'react';const CHAT_WARNING_INFO ="SmythOS can make mistakes, always check your work. We don't store chat history, save important work."; // eslint-disable-line quotes-export const Footer: FC<FooterProps> = (props) => {- const {- chatInputRef,- uploadError,- clearError,- submitDisabled,- showScrollButton,- scrollToBottom,- } = props;+export const Footer: FC = () => {+ const { files, scroll } = useChatStores();+ const { errorMessage, clearError } = files || {};+ const { showScrollButton, scrollToBottom } = scroll || {};return (<div className="w-full max-w-4xl pt-2.5">- {uploadError.show && <ErrorToast message={uploadError.message} onClose={clearError} />}+ {errorMessage && <ErrorToast message={errorMessage} onClose={clearError} />}<div className="relative">{showScrollButton && <ScrollToBottomButton onClick={() => scrollToBottom(true)} />}- <ChatInput ref={chatInputRef} submitDisabled={submitDisabled} />+ <ChatInput /></div><h6 className="py-4 text-center text-xs text-gray-500">{CHAT_WARNING_INFO}</h6>diff --git a/packages/app/src/react/features/ai-chat/components/input.tsx b/packages/app/src/react/features/ai-chat/components/input.tsxindex 0474df82..d4f23ae5 100644--- a/packages/app/src/react/features/ai-chat/components/input.tsx+++ b/packages/app/src/react/features/ai-chat/components/input.tsx@@ -1,8 +1,6 @@import {ChangeEvent,- forwardRef,KeyboardEvent,- PropsWithoutRef,useCallback,useEffect,useImperativeHandle,@@ -13,8 +11,7 @@ import '../styles/index.css';import { AttachmentButton, FileItemPreview, SendButton } from '@react/features/ai-chat/components';import { CHAT_ACCEPTED_FILE_TYPES } from '@react/features/ai-chat/constants';-import { useChatContext } from '@react/features/ai-chat/contexts';-import { useClipboardPaste } from '@react/features/ai-chat/hooks';+import { useChatStores, useClipboardPaste } from '@react/features/ai-chat/hooks';import { createFileFromText } from '@react/features/ai-chat/utils';import {forceScrollToBottomImmediate,@@ -23,11 +20,6 @@ import {import { MAX_CHAT_MESSAGE_LENGTH } from '@react/shared/constants';import { cn } from '@react/shared/utils/general';-interface ChatInputProps extends PropsWithoutRef<JSX.IntrinsicElements['textarea']> {- submitDisabled?: boolean;- maxLength?: number;-}-export interface ChatInputRef {focus: () => void;getValue: () => string;@@ -37,281 +29,281 @@ export interface ChatInputRef {const TEXTAREA_MAX_HEIGHT = 160;const LARGE_TEXT_THRESHOLD = 4000;-export const ChatInput = forwardRef<ChatInputRef, ChatInputProps>(- ({ submitDisabled = false, maxLength = MAX_CHAT_MESSAGE_LENGTH }, ref) => {- const {- files,- removeFile,- clearFiles,- sendMessage,- isGenerating,- stopGenerating,- uploadingFiles,- inputDisabled,- inputPlaceholder,- isInputProcessing,- handleFileDrop,- handleFileChange,- isMaxFilesUploaded,- } = useChatContext();-- const [message, setMessage] = useState('');- const inputRef = useRef<HTMLTextAreaElement>(null);- const fileInputRef = useRef<HTMLInputElement>(null);-- // Debounce ref for textarea height adjustment- const heightAdjustmentTimerRef = useRef<NodeJS.Timeout | null>(null);-- /**- * Adjusts textarea height based on content- * This is an expensive operation, so we debounce it- */- const adjustTextareaHeight = useCallback(() => {- const textarea = inputRef.current;- if (!textarea) return;-- textarea.style.height = 'auto';- const newHeight = Math.min(textarea.scrollHeight, TEXTAREA_MAX_HEIGHT);- textarea.style.height = `${newHeight}px`;- textarea.style.overflowY = newHeight === TEXTAREA_MAX_HEIGHT ? 'auto' : 'hidden';- }, []);-- /**- * Debounced version of textarea height adjustment- * Improves typing performance by batching height calculations- * Delay: 100ms (feels instant but reduces calculations by ~90%)- */- const debouncedAdjustHeight = useCallback(() => {- // Clear existing timer+export const ChatInput = () => {+ const { ref: allRefs, files: filesData, chat, agent } = useChatStores();++ const chatInputRef = allRefs?.input;+ const { isStreaming, isChatCreating, isProcessing, sendMessage, stopGenerating } = chat || {};+ const { data: files, addFiles, removeFile, clearFiles } = filesData || {};++ const maxLength = MAX_CHAT_MESSAGE_LENGTH;+ const isFilesLoading = filesData?.isLoading;+ const isMaxFilesUploaded = files.length >= 10;+ const inputDisabled = isChatCreating || agent.isLoading.agent || isProcessing;+ const inputPlaceholder = agent.data?.name ? `Message ${agent.data.name}...` : 'Message ...';+ const submitDisabled = chat.isChatCreating || agent.isLoading.agent || isFilesLoading;++ const handleFileChange = useCallback(+ (e: ChangeEvent<HTMLInputElement>) => {+ if (!e.target.files?.length) return;+ addFiles(Array.from(e.target.files));+ },+ [addFiles],+ );++ const [message, setMessage] = useState('');+ const inputRef = useRef<HTMLTextAreaElement>(null);+ const fileInputRef = useRef<HTMLInputElement>(null);++ // Debounce ref for textarea height adjustment+ const heightAdjustmentTimerRef = useRef<NodeJS.Timeout | null>(null);++ /**+ * Adjusts textarea height based on content+ * This is an expensive operation, so we debounce it+ */+ const adjustTextareaHeight = useCallback(() => {+ const textarea = inputRef.current;+ if (!textarea) return;++ textarea.style.height = 'auto';+ const newHeight = Math.min(textarea.scrollHeight, TEXTAREA_MAX_HEIGHT);+ textarea.style.height = `${newHeight}px`;+ textarea.style.overflowY = newHeight === TEXTAREA_MAX_HEIGHT ? 'auto' : 'hidden';+ }, []);++ /**+ * Debounced version of textarea height adjustment+ * Improves typing performance by batching height calculations+ * Delay: 100ms (feels instant but reduces calculations by ~90%)+ */+ const debouncedAdjustHeight = useCallback(() => {+ // Clear existing timer+ if (heightAdjustmentTimerRef.current) {+ clearTimeout(heightAdjustmentTimerRef.current);+ }++ // Schedule new adjustment+ heightAdjustmentTimerRef.current = setTimeout(() => {+ adjustTextareaHeight();+ heightAdjustmentTimerRef.current = null;+ }, 100);+ }, [adjustTextareaHeight]);++ useImperativeHandle(+ chatInputRef,+ () => ({+ focus: () => inputRef.current?.focus(),+ getValue: () => message,+ setValue: (content: string) => setMessage(content.slice(0, maxLength)),+ }),+ [maxLength, message],+ );++ /**+ * Adjust height when message changes (debounced for performance)+ * Also cleanup timer on unmount+ */+ useEffect(() => {+ debouncedAdjustHeight();++ // Cleanup function to clear pending timers+ return () => {if (heightAdjustmentTimerRef.current) {clearTimeout(heightAdjustmentTimerRef.current);+ heightAdjustmentTimerRef.current = null;}-- // Schedule new adjustment- heightAdjustmentTimerRef.current = setTimeout(() => {- adjustTextareaHeight();+ };+ }, [message, debouncedAdjustHeight]);++ const handleChange = useCallback(+ (e: ChangeEvent<HTMLTextAreaElement>) => {+ const newValue = e.target.value.slice(0, maxLength);+ setMessage(newValue);+ },+ [maxLength],+ );++ const handleSubmit = useCallback((): void => {+ if (isStreaming) return stopGenerating();++ const trimmedMessage = message.trim();+ if (trimmedMessage.length > 0 || files.length > 0) {+ sendMessage(trimmedMessage, files);+ setMessage('');+ clearFiles();++ // Clear any pending debounced height adjustments+ if (heightAdjustmentTimerRef.current) {+ clearTimeout(heightAdjustmentTimerRef.current);heightAdjustmentTimerRef.current = null;- }, 100);- }, [adjustTextareaHeight]);-- useImperativeHandle(- ref,- () => ({- focus: () => inputRef.current?.focus(),- getValue: () => message,- setValue: (content: string) => setMessage(content.slice(0, maxLength)),- }),- [maxLength, message],- );-- /**- * Adjust height when message changes (debounced for performance)- * Also cleanup timer on unmount- */- useEffect(() => {- debouncedAdjustHeight();-- // Cleanup function to clear pending timers- return () => {- if (heightAdjustmentTimerRef.current) {- clearTimeout(heightAdjustmentTimerRef.current);- heightAdjustmentTimerRef.current = null;- }- };- }, [message, debouncedAdjustHeight]);-- const handleChange = useCallback(- (e: ChangeEvent<HTMLTextAreaElement>) => {- const newValue = e.target.value.slice(0, maxLength);- setMessage(newValue);- },- [maxLength],- );-- const handleSubmit = useCallback((): void => {- if (isGenerating) return stopGenerating();-- const trimmedMessage = message.trim();- if (trimmedMessage.length > 0 || files.length > 0) {- sendMessage(trimmedMessage, files);- setMessage('');- clearFiles();-- // Clear any pending debounced height adjustments- if (heightAdjustmentTimerRef.current) {- clearTimeout(heightAdjustmentTimerRef.current);- heightAdjustmentTimerRef.current = null;- }+ }- // Immediately adjust height after clearing message (no debounce needed)- requestAnimationFrame(() => adjustTextareaHeight());+ // Immediately adjust height after clearing message (no debounce needed)+ requestAnimationFrame(() => adjustTextareaHeight());- if (fileInputRef.current) {- fileInputRef.current.value = '';- }- // Professional scroll to bottom after sending message- // Ensure scroll manager is initialized with the chat container- let chatContainer = document.querySelector('[data-chat-container]') as HTMLElement;+ if (fileInputRef.current) {+ fileInputRef.current.value = '';+ }+ // Professional scroll to bottom after sending message+ // Ensure scroll manager is initialized with the chat container+ let chatContainer = document.querySelector('[data-chat-container]') as HTMLElement;- // Fallback: try to find container by class- if (!chatContainer) {- chatContainer = document.querySelector('.overflow-auto') as HTMLElement;- }+ // Fallback: try to find container by class+ if (!chatContainer) {+ chatContainer = document.querySelector('.overflow-auto') as HTMLElement;+ }- // Fallback: try to find container by scroll-smooth class- if (!chatContainer) {- chatContainer = document.querySelector('.scroll-smooth') as HTMLElement;- }+ // Fallback: try to find container by scroll-smooth class+ if (!chatContainer) {+ chatContainer = document.querySelector('.scroll-smooth') as HTMLElement;+ }- if (chatContainer) {- scrollManager.init(chatContainer);- } else {- // Try to use existing container if any- const existingContainer = scrollManager.getContainer();- if (!existingContainer) {- return; // No container available, skip scroll- }+ if (chatContainer) {+ scrollManager.init(chatContainer);+ } else {+ // Try to use existing container if any+ const existingContainer = scrollManager.getContainer();+ if (!existingContainer) {+ return; // No container available, skip scroll}-- // Reset cooldown to ensure user-initiated scrolls always work- scrollManager.resetForceScrollCooldown();-- // Add a small delay to ensure the message is added to DOM first- setTimeout(() => {- forceScrollToBottomImmediate({- behavior: 'smooth',- delay: 0,- });- }, 150); // 150ms delay to ensure DOM is updated}- }, [message, files, isGenerating, inputDisabled, adjustTextareaHeight]); // eslint-disable-line react-hooks/exhaustive-deps- const handleKeyDown = useCallback(- (e: KeyboardEvent<HTMLTextAreaElement>) => {- if (e.key === 'Enter' && !e.shiftKey) {- e.preventDefault();- !isGenerating && handleSubmit();- }- },- [handleSubmit, isGenerating],- );-- const handleRemoveFile = useCallback(- (index: number): void => {- removeFile(index);- if (fileInputRef.current) {- fileInputRef.current.value = '';- }- },- [removeFile],- );+ // Reset cooldown to ensure user-initiated scrolls always work+ scrollManager.resetForceScrollCooldown();++ // Add a small delay to ensure the message is added to DOM first+ setTimeout(() => {+ forceScrollToBottomImmediate({ behavior: 'smooth', delay: 0 });+ }, 150); // 150ms delay to ensure DOM is updated+ }+ }, [message, files, isStreaming, inputDisabled, adjustTextareaHeight]); // eslint-disable-line react-hooks/exhaustive-deps++ const handleKeyDown = useCallback(+ (e: KeyboardEvent<HTMLTextAreaElement>) => {+ if (e.key === 'Enter' && !e.shiftKey) {+ e.preventDefault();+ !isStreaming && handleSubmit();+ }+ },+ [handleSubmit, isStreaming],+ );- const handleAttachmentClick = useCallback(() => {+ const handleRemoveFile = useCallback(+ (index: number): void => {+ removeFile(index);if (fileInputRef.current) {fileInputRef.current.value = '';- fileInputRef.current.click();}- }, []);-- // useClipboardPaste hook to handle paste events- // it will handle file drops and large text paste- // it will convert large text to file and drop it- // it will handle file drops and large text paste- useClipboardPaste({- onFilePaste: handleFileDrop,- targetRef: inputRef,- largeTextThreshold: LARGE_TEXT_THRESHOLD,- onLargeTextPaste: (text) => {- const file = createFileFromText(text);- handleFileDrop([file.file]);- },- });-- const isMaxLengthReached = message.length === maxLength;- const canSubmit =- !submitDisabled && (message.trim().length > 0 || isGenerating || files.length > 0);-- const handleContainerClick = () => inputRef.current?.focus();-- return (+ },+ [removeFile],+ );++ const handleAttachmentClick = useCallback(() => {+ if (fileInputRef.current) {+ fileInputRef.current.value = '';+ fileInputRef.current.click();+ }+ }, []);++ // useClipboardPaste hook to handle paste events+ // it will handle file drops and large text paste+ // it will convert large text to file and drop it+ // it will handle file drops and large text paste+ useClipboardPaste({+ onFilePaste: addFiles,+ targetRef: inputRef,+ largeTextThreshold: LARGE_TEXT_THRESHOLD,+ onLargeTextPaste: (text) => {+ const file = createFileFromText(text);+ addFiles([file.file]);+ },+ });++ const isMaxLengthReached = message.length === maxLength;+ const canSubmit =+ !submitDisabled && (message.trim().length > 0 || isStreaming || files.length > 0);++ const handleContainerClick = () => inputRef.current?.focus();++ return (+ <div+ className="w-full bg-white border border-solid border-[#e5e5e5] rounded-lg py-1 mt-2.5 text-sm flex flex-col items-start justify-center cursor-text"+ onClick={handleContainerClick}+ >+ {files.length > 0 && (+ <div+ className="flex flex-nowrap gap-2 w-full h-full px-2.5 py-5 overflow-x-auto"+ role="list"+ aria-label="Attached files"+ >+ {files.map((fileWithMetadata, index) => (+ <FileItemPreview+ key={`${fileWithMetadata.id}`}+ file={fileWithMetadata}+ onRemove={() => handleRemoveFile(index)}+ isUploading={isFilesLoading} // .has(fileWithMetadata.id)+ />+ ))}+ </div>+ )}+<div- className="w-full bg-white border border-solid border-[#e5e5e5] rounded-lg py-1 mt-2.5 text-sm flex flex-col items-start justify-center cursor-text"+ className="rounded-lg py-1 px-2.5 flex items-center text-sm w-full min-h-[60px] cursor-text"onClick={handleContainerClick}>- {files.length > 0 && (- <div- className="flex flex-nowrap gap-2 w-full h-full px-2.5 py-5 overflow-x-auto"- role="list"- aria-label="Attached files"- >- {files.map((fileWithMetadata, index) => (- <FileItemPreview- key={`${fileWithMetadata.id}`}- file={fileWithMetadata}- onRemove={() => handleRemoveFile(index)}- isUploading={uploadingFiles.has(fileWithMetadata.id)}- />- ))}- </div>- )}+ <input+ type="file"+ accept={CHAT_ACCEPTED_FILE_TYPES.input}+ className="hidden"+ ref={fileInputRef}+ onChange={handleFileChange}+ multiple+ aria-label="File attachment input"+ onClick={(e) => e.stopPropagation()}+ />+ <textarea+ rows={1}+ ref={inputRef}+ value={message}+ onChange={handleChange}+ onKeyDown={handleKeyDown}+ placeholder={inputPlaceholder}+ maxLength={maxLength}+ className="bg-white border-none outline-none ring-0 focus:outline-none focus:border-none flex-1 max-h-36 resize-none ph-no-capture text-[16px] font-[400] text-gray-900 placeholder:text-gray-500 placeholder:text-[16px] placeholder:font-[400]"+ aria-label="Message input"+ onClick={(e) => e.stopPropagation()}+ /><div- className="rounded-lg py-1 px-2.5 flex items-center text-sm w-full min-h-[60px] cursor-text"- onClick={handleContainerClick}+ className={cn(+ 'text-xs mr-2 w-[75px] text-right flex-shrink-0',+ isMaxLengthReached ? 'text-red-500' : 'text-gray-500',+ )}+ aria-live="polite"+ onClick={(e) => e.stopPropagation()}>- <input- type="file"- accept={CHAT_ACCEPTED_FILE_TYPES.input}- className="hidden"- ref={fileInputRef}- onChange={handleFileChange}- multiple- aria-label="File attachment input"- onClick={(e) => e.stopPropagation()}- />- <textarea- rows={1}- ref={inputRef}- value={message}- onChange={handleChange}- onKeyDown={handleKeyDown}- placeholder={inputPlaceholder}- maxLength={maxLength}- className="bg-white border-none outline-none ring-0 focus:outline-none focus:border-none flex-1 max-h-36 resize-none ph-no-capture text-[16px] font-[400] text-gray-900 placeholder:text-gray-500 placeholder:text-[16px] placeholder:font-[400]"- aria-label="Message input"- onClick={(e) => e.stopPropagation()}- />+ {message.length}/{maxLength}+ </div>- <div- className={cn(- 'text-xs mr-2 w-[75px] text-right flex-shrink-0',- isMaxLengthReached ? 'text-red-500' : 'text-gray-500',- )}- aria-live="polite"- onClick={(e) => e.stopPropagation()}- >- {message.length}/{maxLength}- </div>-- <div onClick={(e) => e.stopPropagation()}>- <AttachmentButton- onClick={handleAttachmentClick}- fileAttachmentDisabled={- isMaxFilesUploaded || inputDisabled || isInputProcessing || isGenerating- }- isMaxFilesUploaded={isMaxFilesUploaded}- />- </div>+ <div onClick={(e) => e.stopPropagation()}>+ <AttachmentButton+ onClick={handleAttachmentClick}+ fileAttachmentDisabled={+ isMaxFilesUploaded || inputDisabled || isProcessing || isStreaming+ }+ isMaxFilesUploaded={isMaxFilesUploaded}+ />+ </div>- <div onClick={(e) => e.stopPropagation()}>- <SendButton- isProcessing={isInputProcessing || isGenerating}- disabled={!canSubmit}- onClick={handleSubmit}- />- </div>+ <div onClick={(e) => e.stopPropagation()}>+ <SendButton+ isProcessing={isProcessing || isStreaming}+ disabled={!canSubmit}+ onClick={handleSubmit}+ /></div></div>- );- },-);+ </div>+ );+};diff --git a/packages/app/src/react/features/ai-chat/components/typewriter.tsx b/packages/app/src/react/features/ai-chat/components/typewriter.tsxindex b86ddd75..8beb7e84 100644--- a/packages/app/src/react/features/ai-chat/components/typewriter.tsx+++ b/packages/app/src/react/features/ai-chat/components/typewriter.tsx@@ -1,7 +1,7 @@import { FC, useEffect, useState } from 'react';import { MarkdownRenderer } from '@react/features/ai-chat/components';-import { useChatContext } from '../contexts';+import { useChatStore } from '@react/features/ai-chat/hooks';interface ITypewriterProps {message: string;@@ -27,7 +27,7 @@ export const Typewriter: FC<ITypewriterProps> = ({const [displayedText, setDisplayedText] = useState('');const [currentIndex, setCurrentIndex] = useState(0);const [lastMessageLength, setLastMessageLength] = useState(0);- const { isGenerating = true } = useChatContext();+ const { isStreaming } = useChatStore('chat') || {};/*** PERFORMANCE OPTIMIZATION:@@ -42,7 +42,7 @@ export const Typewriter: FC<ITypewriterProps> = ({// Handle immediate display when generation is completeuseEffect(() => {- if (!isGenerating && message.length > 0) {+ if (!isStreaming && message.length > 0) {// When generation is complete, show all content immediatelysetDisplayedText(message);setCurrentIndex(message.length);@@ -50,7 +50,7 @@ export const Typewriter: FC<ITypewriterProps> = ({onComplete?.();return;}- }, [isGenerating, message, onComplete]);+ }, [isStreaming, message, onComplete]);/*** SCROLL OPTIMIZATION:diff --git a/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx b/packages/app/src/react/features/ai-chat/contexts/chat-context.tsxindex 79d7cb5d..37e022d9 100644--- a/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx@@ -2,7 +2,7 @@import { ChatInputRef } from '@react/features/ai-chat/components/input';import { IChatMessage, IMessageFile } from '@react/features/ai-chat/types/chat.types';import { AgentDetails, AgentSettings } from '@react/shared/types/agent-data.types';-import { createContext, MutableRefObject } from 'react';+import { createContext, Dispatch, MutableRefObject, SetStateAction } from 'react';export interface IChatContext {ref: { input?: MutableRefObject<ChatInputRef>; container?: MutableRefObject<HTMLDivElement> };@@ -17,6 +17,9 @@ export interface IChatContext {data: IMessageFile[];addFiles: (newFiles: File[]) => Promise<void>;removeFile: (index: number) => Promise<void>;+ clearError: () => void;+ clearFiles: () => void;+ clearAll: () => void;};chat: {// State@@ -33,6 +36,15 @@ export interface IChatContext {clearMessages: () => void;resetSession: () => Promise<void>;};+ scroll: {+ showScrollButton: boolean;+ shouldAutoScroll: boolean;+ handleScroll: () => void;+ scrollToBottom: (smooth?: boolean) => void;+ smartScrollToBottom: (smooth?: boolean) => void;+ setShowScrollButton: Dispatch<SetStateAction<boolean>>;+ setShouldAutoScroll: Dispatch<SetStateAction<boolean>>;+ };// Model override (temporary, not saved to agent config)modelOverride: string | null;setModelOverride: (model: string | null) => void;@@ -47,6 +59,9 @@ export const ChatContext = createContext<IChatContext>({errorMessage: '',addFiles: async () => {},removeFile: async () => {},+ clearError: () => {},+ clearFiles: () => {},+ clearAll: () => {},},chat: {isChatCreating: false,@@ -60,6 +75,15 @@ export const ChatContext = createContext<IChatContext>({clearMessages: () => {},resetSession: async () => {},},+ scroll: {+ showScrollButton: false,+ shouldAutoScroll: true,+ handleScroll: () => {},+ scrollToBottom: () => {},+ smartScrollToBottom: () => {},+ setShowScrollButton: () => {},+ setShouldAutoScroll: () => {},+ },modelOverride: null,setModelOverride: () => {},});diff --git a/packages/app/src/react/features/ai-chat/contexts/index.new.tsx b/packages/app/src/react/features/ai-chat/contexts/index.new.tsxindex 72d163e8..d4134030 100644--- a/packages/app/src/react/features/ai-chat/contexts/index.new.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/index.new.tsx@@ -4,6 +4,7 @@ import {useAgentSettings,useAttachments,useCreateChatMutation,+ useScrollToBottom,useUpdateAgentSettingsMutation,} from '@react/features/ai-chat/hooks';import { useAgent } from '@react/shared/hooks/agent';@@ -152,6 +153,11 @@ export const ChatContextProvider: FC<IProps> = ({ children }) => {Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);}, [createSession, clearMessages, files, stopGenerating, inputRef]);+ // ============================================================================+ // SCROLL BEHAVIOR+ // ============================================================================+ const scroll = useScrollToBottom(containerRef);+// ============================================================================// LIFECYCLE EFFECTS// ============================================================================@@ -203,6 +209,8 @@ export const ChatContextProvider: FC<IProps> = ({ children }) => {resetSession,},+ scroll,+modelOverride,setModelOverride,}),@@ -226,6 +234,8 @@ export const ChatContextProvider: FC<IProps> = ({ children }) => {clearMessages,resetSession,+ scroll,+modelOverride,setModelOverride,],diff --git a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsxindex 59ed4f99..879fa149 100644--- a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx+++ b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx@@ -10,7 +10,7 @@ import {} from '@react/features/ai-chat/components';import { ChatProvider } from '@react/features/ai-chat/contexts';import { ChatContextProvider } from '@react/features/ai-chat/contexts/index.new';-import { useAgentChatContext, useScrollToBottom } from '@react/features/ai-chat/hooks';+import { useAgentChatContext } from '@react/features/ai-chat/hooks';/*** Agent Chat Page Component@@ -29,20 +29,15 @@ const AgentChatPage = () => {// UI refs for input focus and scroll managementconst chatInputRef = useRef<ChatInputRef>(null);- const chatContainerRef = useRef<HTMLDivElement>(null);// ============================================================================// CHAT CONTEXT SETUP// ============================================================================// All chat logic is now encapsulated in this single hook- const { agent, isLoading, chatContextValue, sharedMessagesHistory, handleFileDrop } =- useAgentChatContext({ agentId: agentId || '', inputRef: chatInputRef });-- // ============================================================================- // SCROLL BEHAVIOR- // ============================================================================- const { smartScrollToBottom, scrollToBottom, showScrollButton, ...scroll } =- useScrollToBottom(chatContainerRef);+ const { isLoading, chatContextValue } = useAgentChatContext({+ agentId: agentId || '',+ inputRef: chatInputRef,+ });// ============================================================================// UI EFFECTS@@ -64,26 +59,8 @@ const AgentChatPage = () => {<ChatProvider value={chatContextValue}><Container><ChatHeader />-- <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- }- />+ <Chats />+ <Footer /></Container></ChatProvider></ChatContextProvider>