Skip to content

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.

Refactor AI Chat Components and Remove Deprecated Files

Salman-Ahamedb727ccef538e
diff --git a/packages/app/src/react/features/ai-chat/components/chat/chat.tsx b/packages/app/src/react/features/ai-chat/components/chat/chat.tsx
index 0690c0f9..b6cdaec1 100644
--- a/packages/app/src/react/features/ai-chat/components/chat/chat.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chat/chat.tsx
@@ -2,15 +2,15 @@ import { FC, memo } from 'react';
import {
ErrorMessage,
+ Loading,
MetaMessage,
- ReplyLoader,
SystemMessage,
UserMessage,
} from '@react/features/ai-chat/components';
+import { MESSAGE_TYPES } from '@react/features/ai-chat/constants';
+import { IMessage } from '@react/features/ai-chat/types/chat';
-import { MESSAGE_TYPES } from '../../constants';
import '../../styles/index.css';
-import { IMessage } from '../../types/chat';
interface IChatProps extends IMessage {
avatar: string;
@@ -18,16 +18,6 @@ interface IChatProps extends IMessage {
scrollToBottom?: () => void;
}
-/**
- * Chat Component (Memoized for Performance)
- * Renders appropriate message component based on message type and state
- *
- * Memoization prevents unnecessary re-renders of unchanged messages
- * Critical for performance in long conversations (100+ messages)
- *
- * @param props - Chat message properties
- * @returns Appropriate message component
- */
export const Chat: FC<IChatProps> = memo((props) => {
const { type, attachments, avatar, content, metaMessages, onRetryClick, scrollToBottom } = props;
@@ -35,7 +25,7 @@ export const Chat: FC<IChatProps> = memo((props) => {
case MESSAGE_TYPES.USER:
return <UserMessage message={content} files={attachments} />;
case MESSAGE_TYPES.LOADING:
- return <ReplyLoader />;
+ return <Loading />;
case MESSAGE_TYPES.META:
return <MetaMessage data={{ avatar, metaMessages }} scrollToBottom={scrollToBottom} />;
case MESSAGE_TYPES.SYSTEM:
diff --git a/packages/app/src/react/features/ai-chat/components/chat/chats-with-group.tsx b/packages/app/src/react/features/ai-chat/components/chat/chats-with-group.tsx
deleted file mode 100644
index 9ea8ccfd..00000000
--- a/packages/app/src/react/features/ai-chat/components/chat/chats-with-group.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-/**
- * MessageTurnGroup Component (Memoized for Performance)
- * Groups messages by turnId and provides a single copy button for the entire group
- *
- * Memoization prevents re-rendering of completed conversation turns
- * Critical for long conversations with multiple turns
- */
-
-import { Tooltip, TooltipContent, TooltipTrigger } from '@src/react/shared/components/ui/tooltip';
-import { FC, memo, useRef, useState } from 'react';
-import { FaCheck, FaRegCopy } from 'react-icons/fa6';
-
-import { IChatMessage } from '@react/features/ai-chat/types/chat.types';
-import { Chat } from './chat';
-
-interface IProps {
- messages: IChatMessage[]; // Messages in this conversation turn (all share same turnId)
- avatar?: string; // Agent avatar URL
- onRetryClick?: () => void; // Retry callback for error messages
- scrollToBottom: (smooth?: boolean) => void; // eslint-disable-line no-unused-vars
-}
-
-/**
- * Groups messages from a single conversation turn
- * Displays all messages and provides a single copy button for the entire group
- */
-export const ChatsTurnGroup: FC<IProps> = memo((props) => {
- const { messages, avatar, onRetryClick, scrollToBottom } = props;
- const [copied, setCopied] = useState(false);
- const groupRef = useRef<HTMLDivElement>(null);
-
- // Check if this group contains any system messages (for copy button visibility)
- const hasSystemMessages = messages.some(
- (msg) => msg.type === 'system' && msg.message && msg.message.trim() !== '',
- );
-
- // Check if the last message is complete (not loading or thinking)
- const lastMessage = messages[messages.length - 1];
- const isComplete =
- lastMessage && lastMessage.type !== 'loading' && lastMessage.type !== 'thinking';
-
- /**
- * Copies all system message content from this group
- */
- const handleCopyGroup = () => {
- // Collect all system message content
- const allContent = messages
- .filter((msg) => msg.type === 'system' && msg.message && msg.message.trim() !== '')
- .map((msg) => msg.message)
- .join('\n\n'); // Join with double newline for separation
-
- if (allContent) {
- // Use modern Clipboard API
- navigator.clipboard
- .writeText(allContent)
- .then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- })
- .catch((err) => {
- // Fallback to old method
- console.error('Failed to copy using Clipboard API: ', err); // eslint-disable-line no-console
-
- // Create temporary textarea
- const textarea = document.createElement('textarea');
- textarea.value = allContent;
- textarea.style.position = 'fixed';
- textarea.style.opacity = '0';
- document.body.appendChild(textarea);
- textarea.select();
-
- try {
- document.execCommand('copy');
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } catch (execErr) {
- console.error('Failed to copy text: ', execErr); // eslint-disable-line no-console
- }
-
- document.body.removeChild(textarea);
- });
- }
- };
-
- return (
- <div ref={groupRef} className="message-turn-group relative">
- {/* Render all messages in this turn */}
- <div className="space-y-2.5">
- {messages.map((message, index) => {
- const isLastInGroup = index === messages.length - 1;
- const canRetry = message.type === 'error' && isLastInGroup && onRetryClick;
-
- return (
- <Chat
- key={message.id || index}
- {...message}
- avatar={avatar}
- onRetryClick={canRetry ? onRetryClick : undefined}
- scrollToBottom={scrollToBottom}
- />
- );
- })}
- </div>
-
- {/* Single copy button for the entire group */}
- {hasSystemMessages && isComplete && (
- <div className="ps-2.5 pb-2.5">
- <Tooltip>
- <TooltipTrigger asChild>
- <button
- onClick={handleCopyGroup}
- className="text-gray-500 hover:text-gray-700 transition-colors"
- aria-label="Copy all messages"
- >
- {copied ? <FaCheck /> : <FaRegCopy />}
- </button>
- </TooltipTrigger>
- <TooltipContent side="bottom">
- <p>{copied ? 'Copied!' : 'Copy all'}</p>
- </TooltipContent>
- </Tooltip>
- </div>
- )}
- </div>
- );
-});
diff --git a/packages/app/src/react/features/ai-chat/components/chat/index.ts b/packages/app/src/react/features/ai-chat/components/chat/index.ts
index d7344179..c6cc82c0 100644
--- a/packages/app/src/react/features/ai-chat/components/chat/index.ts
+++ b/packages/app/src/react/features/ai-chat/components/chat/index.ts
@@ -1,10 +1,9 @@
export * from './chat';
export * from './chats';
-export * from './chats-with-group';
export * from './code-block';
export * from './error-message';
export * from './markdown-renderer';
-export * from './reply-loader';
+export * from './loading';
export * from './system-message';
export * from './thinking-message';
export * from './typewriter';
diff --git a/packages/app/src/react/features/ai-chat/components/chat/reply-loader.tsx b/packages/app/src/react/features/ai-chat/components/chat/loading.tsx
similarity index 83%
rename from packages/app/src/react/features/ai-chat/components/chat/reply-loader.tsx
rename to packages/app/src/react/features/ai-chat/components/chat/loading.tsx
index f82c7099..14f391f6 100644
--- a/packages/app/src/react/features/ai-chat/components/chat/reply-loader.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chat/loading.tsx
@@ -1,4 +1,4 @@
-export const ReplyLoader = () => (
+export const Loading = () => (
<div className="flex items-center gap-2 pr-[100px]">
<div className="rounded-t-3xl rounded-br-3xl px-6 py-4">
<div className="chat-loader" />
diff --git a/packages/app/src/react/features/ai-chat/components/chat/thinking-message.tsx b/packages/app/src/react/features/ai-chat/components/chat/thinking-message.tsx
index 9a005561..4c44b219 100644
--- a/packages/app/src/react/features/ai-chat/components/chat/thinking-message.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chat/thinking-message.tsx
@@ -26,11 +26,6 @@ const blinkAnimation = `
}
`;
-/**
- * ThinkingMessage Component
- * Manages thinking message cycling internally using ThinkingMessageManager
- * Receives metaMessages from parent and handles the cycling logic
- */
export const MetaMessage: FC<IProps> = ({ data, scrollToBottom }) => {
const { avatar, metaMessages } = data;
@@ -41,30 +36,19 @@ export const MetaMessage: FC<IProps> = ({ data, scrollToBottom }) => {
scrollToBottom?.();
}, [scrollToBottom]);
- /**
- * Effect to manage thinking message lifecycle
- * Starts/updates cycling when metaMessages are received
- * The ThinkingMessageManager handles priority internally (status > tools > general)
- * Stops when component unmounts
- */
useEffect(() => {
const manager = thinkingManagerRef.current;
- // Check if statusMessage exists - if yes, just display formatted, no cycling
if (metaMessages?.statusMessage) {
- // Format and display statusMessage directly, no thinkingManager needed
const formatted = formatStatusMessage(metaMessages.statusMessage);
setThinkingMessage(formatted);
- manager.stop(); // Stop any existing cycling
+ manager.stop();
return;
}
- // No statusMessage, check for toolName
const toolName = metaMessages?.title || metaMessages?.functionCall?.name;
-
manager.start(setThinkingMessage, toolName || '');
- // Cleanup: stop thinking manager when component unmounts
return () => manager.stop();
}, [metaMessages]);
@@ -72,7 +56,6 @@ export const MetaMessage: FC<IProps> = ({ data, scrollToBottom }) => {
<>
<style>{blinkAnimation}</style>
<div className="flex items-center gap-3 px-3">
- {/* Avatar inside the bubble */}
<div className="flex-shrink-0">
<div className="size-6 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden">
{avatar ? (
@@ -85,7 +68,6 @@ export const MetaMessage: FC<IProps> = ({ data, scrollToBottom }) => {
</div>
</div>
- {/* Message text inside the bubble */}
<div className="flex-1">
<span className="text-sm text-gray-500 font-medium smooth-blink-text">
{thinkingMessage}
diff --git a/packages/app/src/react/features/ai-chat/components/chat/typewriter.tsx b/packages/app/src/react/features/ai-chat/components/chat/typewriter.tsx
index 8beb7e84..efadf4f4 100644
--- a/packages/app/src/react/features/ai-chat/components/chat/typewriter.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chat/typewriter.tsx
@@ -12,10 +12,6 @@ interface ITypewriterProps {
onTypingProgress?: () => void;
}
-/**
- * Typewriter component that displays text character by character with typing animation
- * Similar to ChatGPT's typing effect
- */
export const Typewriter: FC<ITypewriterProps> = ({
message,
onComplete,
@@ -29,43 +25,17 @@ export const Typewriter: FC<ITypewriterProps> = ({
const [lastMessageLength, setLastMessageLength] = useState(0);
const { isStreaming } = useChatStore('chat') || {};
- /**
- * 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
+ const TYPING_SPEED = 0;
- // Handle immediate display when generation is complete
useEffect(() => {
if (!isStreaming && message.length > 0) {
- // When generation is complete, show all content immediately
setDisplayedText(message);
setCurrentIndex(message.length);
-
onComplete?.();
return;
}
}, [isStreaming, message, onComplete]);
- /**
- * 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) {
setDisplayedText(message);
@@ -74,7 +44,6 @@ export const Typewriter: FC<ITypewriterProps> = ({
return;
}
- // Skip animation only for very short messages (less than 3 characters) for instant display
if (message.length < 3) {
setDisplayedText(message);
setCurrentIndex(message.length);
@@ -83,23 +52,12 @@ export const Typewriter: FC<ITypewriterProps> = ({
}
if (currentIndex < message.length) {
- /**
- * 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 instantly
-
+ const batchSize = message.length - currentIndex;
const charsToAdd = message.slice(currentIndex, currentIndex + batchSize);
const timer = setTimeout(() => {
setDisplayedText((prevText) => prevText + charsToAdd);
setCurrentIndex((prevIndex) => prevIndex + batchSize);
- // Trigger scroll during typing progress
onTypingProgress?.();
}, TYPING_SPEED);
@@ -119,7 +77,6 @@ export const Typewriter: FC<ITypewriterProps> = ({
TYPING_SPEED,
]);
- // Reset only when message length decreases (new message) or when message is empty
useEffect(() => {
if (message.length < lastMessageLength || message === '') {
setDisplayedText('');
diff --git a/packages/app/src/react/features/ai-chat/components/chat/user-message.tsx b/packages/app/src/react/features/ai-chat/components/chat/user-message.tsx
index 737632d0..46f5dc2a 100644
--- a/packages/app/src/react/features/ai-chat/components/chat/user-message.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chat/user-message.tsx
@@ -2,20 +2,12 @@ import { FC } from 'react';
import { IAttachment } from '../../types/chat';
import { FileItemPreview } from '../common/FileItemPreview';
-/**
- * User Message Component Properties
- */
-interface IUserMessage {
+interface IProps {
message: string;
files?: IAttachment[];
}
-/**
- * User Message Component
- * Displays user's message with optional file attachments
- * Message bubble automatically hidden if message is empty
- */
-export const UserMessage: FC<IUserMessage> = ({ message, files }) => {
+export const UserMessage: FC<IProps> = ({ message, files }) => {
const hasFiles = files && files.length > 0;
return (
diff --git a/packages/app/src/react/features/ai-chat/components/common/FileItemPreview.tsx b/packages/app/src/react/features/ai-chat/components/common/FileItemPreview.tsx
index 4215c2c2..d428ad35 100644
--- a/packages/app/src/react/features/ai-chat/components/common/FileItemPreview.tsx
+++ b/packages/app/src/react/features/ai-chat/components/common/FileItemPreview.tsx
@@ -11,7 +11,6 @@ import {
} from 'react-icons/fa6';
import type { IAttachment } from '../../types/chat';
-/** Map of file extensions to their corresponding icons */
const FILE_ICONS: Record<string, ReactElement> = {
pdf: <FaRegFilePdf className="text-white text-xl" />,
doc: <FaRegFileWord className="text-white text-xl" />,
@@ -33,17 +32,12 @@ const FILE_ICONS: Record<string, ReactElement> = {
txt: <FaRegFileLines className="text-white text-xl" />,
};
-/** Default icon for unknown file types */
const DEFAULT_ICON = <FaRegFileLines className="text-white text-xl" />;
interface IRemoveButtonProps {
onRemove: () => void;
}
-/**
- * Remove button component for file preview
- * Shows on hover with a close icon
- */
const RemoveButton: FC<IRemoveButtonProps> = memo(({ onRemove }) => (
<button
onClick={onRemove}
@@ -56,28 +50,13 @@ const RemoveButton: FC<IRemoveButtonProps> = memo(({ onRemove }) => (
RemoveButton.displayName = 'RemoveButton';
-/**
- * Props for FileItemPreview component
- * Uses IAttachment for file data, onRemove presence determines if removable
- */
export interface IFileItemPreviewProps {
- /** Attachment data containing file info */
attachment: IAttachment;
- /** If provided, shows remove button. If not, component is readonly */
onRemove?: () => void;
- /** Shows upload spinner overlay when true */
isUploading?: boolean;
}
-/**
- * Extracts file extension from filename or URL
- * @param fileName - The name of the file
- * @param url - Optional URL to extract extension from
- * @param blobUrl - Optional blob URL to extract extension from
- * @returns Lowercase file extension or empty string
- */
const getFileExtension = (fileName: string, url?: string, blobUrl?: string | null): string => {
- // Try to get extension from filename first
if (fileName) {
const ext = fileName.split('.').pop();
if (ext) {
@@ -85,7 +64,6 @@ const getFileExtension = (fileName: string, url?: string, blobUrl?: string | nul
}
}
- // Fallback to URL if filename doesn't have extension
const urlToCheck = url || blobUrl;
if (urlToCheck) {
const urlPath = urlToCheck.split('/').pop() || urlToCheck.split('\\').pop() || '';
@@ -99,65 +77,35 @@ const getFileExtension = (fileName: string, url?: string, blobUrl?: string | nul
return '';
};
-/**
- * Checks if the given MIME type is an image type
- * @param mimeType - The MIME type to check
- * @returns True if the type is an image
- */
const isImageType = (mimeType: string): boolean => {
return mimeType.startsWith('image/');
};
-/**
- * Gets the preview URL for an attachment
- * Prioritizes blob URL, then creates object URL from file, then falls back to url
- * @param attachment - The attachment to get preview URL for
- * @returns Preview URL or null if not available
- */
const getPreviewUrl = (attachment: IAttachment): string | null => {
- // Prefer blobUrl if available
if (attachment.blobUrl) {
return attachment.blobUrl;
}
- // Create object URL from File if available
if (attachment.file) {
return URL.createObjectURL(attachment.file);
}
- // Fallback to url
return attachment.url || null;
};
-/**
- * FileItemPreview component displays a preview of an attached file
- * - Shows image thumbnail for image files
- * - Shows file icon and name for other file types
- * - Optional remove button controlled by onRemove prop presence
- * - Optional upload spinner overlay
- */
export const FileItemPreview: FC<IFileItemPreviewProps> = memo(
({ attachment, onRemove, isUploading = false }) => {
const { name, type, file, url, blobUrl } = attachment;
- // State for image preview URL
const [preview, setPreview] = useState<string | null>(() => {
- // Initialize with blobUrl or url for immediate display
return blobUrl || url || null;
});
- // Extract file extension from name or URLs
const fileExtension = useMemo(() => getFileExtension(name, url, blobUrl), [name, url, blobUrl]);
-
- // Get appropriate icon based on file extension
const fileIcon = useMemo(() => FILE_ICONS[fileExtension] || DEFAULT_ICON, [fileExtension]);
-
- // Check if file is an image based on MIME type
const isImage = useMemo(() => isImageType(type), [type]);
- // Effect to handle preview URL creation and cleanup
useEffect(() => {
- // Skip if not an image
if (!isImage) {
setPreview(null);
return;
@@ -166,7 +114,6 @@ export const FileItemPreview: FC<IFileItemPreviewProps> = memo(
const previewUrl = getPreviewUrl(attachment);
setPreview(previewUrl);
- // Cleanup: revoke object URL if we created one from file
return () => {
if (previewUrl && file && !blobUrl && !url) {
URL.revokeObjectURL(previewUrl);
@@ -174,11 +121,7 @@ export const FileItemPreview: FC<IFileItemPreviewProps> = memo(
};
}, [isImage, attachment, file, blobUrl, url]);
- /**
- * Handles image load error by trying alternative sources
- */
const handleImageError = () => {
- // Try creating blob URL from file if available
if (file && isImageType(file.type)) {
try {
const newBlobUrl = URL.createObjectURL(file);
@@ -189,13 +132,11 @@ export const FileItemPreview: FC<IFileItemPreviewProps> = memo(
}
}
- // Try using the URL if it's a valid http(s) URL
if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
if (preview !== url) setPreview(url);
} else setPreview(null);
};
- // Render image preview for image files
if (isImage) {
return (
<div className="relative inline-block size-16 min-w-16 min-h-16 group mt-4">
@@ -225,8 +166,6 @@ export const FileItemPreview: FC<IFileItemPreviewProps> = memo(
);
}
- // Render file icon preview for non-image files
-
return (
<div className="relative inline-block group mt-4">
{onRemove && (
diff --git a/packages/app/src/react/features/ai-chat/components/common/file-item-preview.tsx b/packages/app/src/react/features/ai-chat/components/common/file-item-preview.tsx
deleted file mode 100644
index f6352478..00000000
--- a/packages/app/src/react/features/ai-chat/components/common/file-item-preview.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-import { IMessageFile } from '@react/features/ai-chat/types/chat.types';
-import { CloseIcon } from '@src/react/features/ai-chat/components/common/icons';
-import classNames from 'classnames';
-import { FC, useEffect, useMemo, useState } from 'react';
-import {
- FaRegFileAudio,
- FaRegFileCode,
- FaRegFileExcel,
- FaRegFileLines,
- FaRegFilePdf,
- FaRegFileVideo,
- FaRegFileWord,
-} from 'react-icons/fa6';
-
-interface FileItemPreviewProps {
- file: IMessageFile;
- onRemove?: () => void;
- isUploading?: boolean;
- fileKey?: string;
- isReadOnly?: boolean;
- inChatBubble?: boolean; // Indicates if the preview is being rendered inside a chat bubble
-}
-
-const commonProps = { className: 'text-white', fontSize: 20 };
-const DEFAULT_ICON = <FaRegFileLines {...commonProps} />;
-const FILE_ICONS = {
- pdf: <FaRegFilePdf {...commonProps} />,
- doc: <FaRegFileWord {...commonProps} />,
- docx: <FaRegFileWord {...commonProps} />,
- xls: <FaRegFileExcel {...commonProps} />,
- xlsx: <FaRegFileExcel {...commonProps} />,
- csv: <FaRegFileExcel {...commonProps} />,
- mp3: <FaRegFileAudio {...commonProps} />,
- wav: <FaRegFileAudio {...commonProps} />,
- ogg: <FaRegFileAudio {...commonProps} />,
- mp4: <FaRegFileVideo {...commonProps} />,
- avi: <FaRegFileVideo {...commonProps} />,
- mov: <FaRegFileVideo {...commonProps} />,
- js: <FaRegFileCode {...commonProps} />,
- ts: <FaRegFileCode {...commonProps} />,
- py: <FaRegFileCode {...commonProps} />,
- java: <FaRegFileCode {...commonProps} />,
- cpp: <FaRegFileCode {...commonProps} />,
- txt: <FaRegFileLines {...commonProps} />,
-};
-
-const RemoveButton: FC<{ onRemove: () => void }> = ({ onRemove }) => (
- <button
- onClick={onRemove}
- className="absolute -top-2 -right-2 bg-white rounded-full p-1 text-gray-500 hover:text-gray-700 border border-gray-200 opacity-0 group-hover:opacity-100 transition-opacity z-10"
- >
- <CloseIcon />
- </button>
-);
-
-export const FileItemPreviews: FC<FileItemPreviewProps> = ({
- file,
- onRemove,
- isUploading,
- isReadOnly = false,
- inChatBubble = false,
-}) => {
- const previewFile = file.file ?? file?.metadata?.publicUrl;
- const [preview, setPreview] = useState<string | null>(null);
-
- const fileExtension = useMemo(
- () => file.file?.name?.split('.').pop()?.toLowerCase(),
- [file.file?.name],
- );
-
- const fileIcon = useMemo(() => FILE_ICONS[fileExtension] || DEFAULT_ICON, [fileExtension]);
-
- useEffect(() => {
- return () => {
- if (preview) {
- URL.revokeObjectURL(preview);
- }
- };
- }, [preview]);
-
- useEffect(() => {
- if (previewFile instanceof File && previewFile.type.startsWith('image/')) {
- const objectUrl = URL.createObjectURL(previewFile);
- setPreview(objectUrl);
- }
- }, [file]); // eslint-disable-line react-hooks/exhaustive-deps
-
- const isImage = useMemo(
- () => file.file?.type?.startsWith('image/') || file.metadata?.fileType?.startsWith('image/'),
- [file.file?.type, file.metadata?.fileType],
- );
-
- if (isImage) {
- return (
- <div className="relative group w-16 h-16 min-w-[4rem] min-h-[4rem]">
- {preview && (
- <img
- src={preview}
- alt={file.file?.name || 'Image preview'}
- className="w-full h-full object-cover rounded-lg"
- />
- )}
- {isUploading && (
- <div className="absolute inset-0 bg-black bg-opacity-50 rounded-lg flex items-center justify-center">
- <div className="animate-spin rounded-full h-6 w-6 border-solid border-2 border-white border-t-transparent"></div>
- </div>
- )}
- {!isReadOnly && !inChatBubble && <RemoveButton onRemove={onRemove} />}
- </div>
- );
- }
-
- return (
- <div className="relative group">
- {!isReadOnly && !inChatBubble && <RemoveButton onRemove={onRemove} />}
- <div
- className={classNames(
- 'flex items-center gap-4 text-sm bg-white rounded-lg border border-gray-200 border-solid p-2 overflow-hidden w-56 min-w-[10rem] h-16',
- )}
- >
- <div className="flex items-center justify-center bg-primary-100 rounded-lg p-2 flex-shrink-0">
- {isUploading ? (
- <div className="animate-spin rounded-full h-5 w-5 border-2 border-white border-t-transparent"></div>
- ) : (
- fileIcon
- )}
- </div>
- <div className="flex flex-col gap-1 min-w-0">
- <span className="truncate font-semibold">{file.file?.name}</span>
- <span className="text-gray-400">{file.file?.name.split('.').pop()?.toUpperCase()}</span>
- </div>
- </div>
- </div>
- );
-};
diff --git a/packages/app/src/react/features/ai-chat/components/header/header-actions.tsx b/packages/app/src/react/features/ai-chat/components/header/header-actions.tsx
index 1a46d209..4616ae9f 100644
--- a/packages/app/src/react/features/ai-chat/components/header/header-actions.tsx
+++ b/packages/app/src/react/features/ai-chat/components/header/header-actions.tsx
@@ -5,19 +5,8 @@ import { Link } from 'react-router-dom';
import { CloseIcon } from '@react/features/ai-chat/components';
import { Tooltip, TooltipContent, TooltipTrigger } from '@react/shared/components/ui/tooltip';
-/**
- * Props for HeaderActions component
- */
-interface IProps {
- onNewChat: () => void;
-}
+type IProps = { onNewChat: () => void };
-/**
- * HeaderActions Component
- * Renders action buttons in chat header (New Chat, Exit)
- *
- * @param onNewChat - Callback to reset chat session
- */
export const HeaderActions: FC<IProps> = ({ onNewChat }) => (
<div className="flex items-center justify-center gap-2">
<Tooltip>
diff --git a/packages/app/src/react/features/ai-chat/components/header/main.tsx b/packages/app/src/react/features/ai-chat/components/header/main.tsx
index afe91f29..f57553c9 100644
--- a/packages/app/src/react/features/ai-chat/components/header/main.tsx
+++ b/packages/app/src/react/features/ai-chat/components/header/main.tsx
@@ -9,9 +9,6 @@ import { cn } from '@react/shared/utils/general';
import { HeaderActions } from './header-actions';
import { ModelDropdown } from './model-dropdown';
-/**
- * Model agent data structure from API
- */
interface ModelAgent {
id: string;
name: string;
@@ -19,42 +16,25 @@ interface ModelAgent {
description: string;
}
-/**
- * Fetches model agents from API
- * Used to determine if current agent is a "default model agent" with fixed model
- */
const fetchModelAgents = async (): Promise<ModelAgent[]> => {
const response = await fetch('/api/page/agents/models');
const data = await response.json();
return data.agents;
};
-/**
- * ChatHeader Component
- * Main header for chat interface displaying agent info and model selection
- *
- * Features:
- * - Agent avatar and name display
- * - LLM model selection dropdown (disabled for default model agents)
- * - New Chat and Exit action buttons
- */
-export const ChatHeader: FC = () => {
+export const Header: FC = () => {
const { agent: agentData, chat, modelOverride, setModelOverride } = useChatStores() || {};
const { data: agent, settings, isLoading } = agentData || {};
const avatar = settings?.avatar;
- // Fetch model agents to check if current agent is a default model agent
const { data: modelAgents } = useQuery<ModelAgent[]>({
queryKey: ['modelAgents'],
queryFn: fetchModelAgents,
refetchOnWindowFocus: false,
});
- // Default model agents have fixed models that cannot be changed
const isModelAgent = modelAgents?.some((modelAgent) => modelAgent.id === agent?.id) ?? false;
-
- // Use override if set, otherwise use agent's default model
const currentModel = modelOverride || settings?.chatGptModel || '';
return (
@@ -91,18 +71,11 @@ export const ChatHeader: FC = () => {
);
};
-/**
- * Props for AgentAvatar component
- */
interface AgentAvatarProps {
avatar: string | undefined;
isLoading: boolean;
}
-/**
- * AgentAvatar Component
- * Displays agent's avatar with loading skeleton
- */
const AgentAvatar: FC<AgentAvatarProps> = ({ avatar, isLoading }) => (
<figure>
{isLoading ? (
@@ -117,19 +90,12 @@ const AgentAvatar: FC<AgentAvatarProps> = ({ avatar, isLoading }) => (
</figure>
);
-/**
- * Props for AgentName component
- */
interface AgentNameProps {
name: string | undefined;
isAgentLoading: boolean;
isSettingsLoading: boolean;
}
-/**
- * AgentName Component
- * Displays agent's name with loading skeleton
- */
const AgentName: FC<AgentNameProps> = ({ name, isAgentLoading, isSettingsLoading }) => {
if (isAgentLoading) {
return (
diff --git a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/index.tsx b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/index.tsx
index ac490fa3..290c7542 100644
--- a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/index.tsx
+++ b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/index.tsx
@@ -12,9 +12,6 @@ import { getBadgeFromTags, ILLMModel } from '@react/features/ai-chat/utils';
import { ModelPanel } from './model-panel';
import { ProviderPanel } from './provider-panel';
-/**
- * Props for ModelDropdown component
- */
interface IProps {
currentModel: string;
isModelAgent: boolean;
@@ -22,32 +19,15 @@ interface IProps {
onModelChange: (model: string) => void; // eslint-disable-line no-unused-vars
}
-/**
- * ModelDropdown Component
- * Two-panel dropdown for LLM model selection with provider grouping
- * Left panel: Provider list, Right panel: Models for selected provider
- *
- * @param currentModel - Currently selected model ID
- * @param isModelAgent - Whether this is a default model agent (disables dropdown)
- * @param isDisabled - External disabled state
- * @param onModelChange - Callback when user selects a new model
- */
-export const ModelDropdown: FC<IProps> = ({
- currentModel,
- isModelAgent,
- isDisabled,
- onModelChange,
-}) => {
+export const ModelDropdown: FC<IProps> = (props) => {
+ const { currentModel, isModelAgent, isDisabled, onModelChange } = props;
+
const [llmModels, setLlmModels] = useState<Array<ILLMModel>>([]);
const [isModelsLoading, setIsModelsLoading] = useState<boolean>(true);
const [provider, setProvider] = useState<string>(currentModel);
const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);
const dropdownRef = useRef<HTMLDivElement>(null);
- /**
- * Initializes LLM models store on mount
- * Fetches models with 'tools' feature capability
- */
useEffect(() => {
llmModelsStore
.getState()
@@ -69,9 +49,6 @@ export const ModelDropdown: FC<IProps> = ({
});
}, [currentModel]);
- /**
- * Closes dropdown when clicking outside
- */
useEffect(() => {
const handleClickOutside = (event: MouseEvent): void => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
@@ -84,11 +61,6 @@ export const ModelDropdown: FC<IProps> = ({
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [isDropdownOpen]);
- /**
- * Handles model selection
- * Updates context state only - does NOT modify agent configuration
- * Model override is sent with each request via x-model-id header
- */
const handleModelChange = useCallback(
(newModel: string) => {
onModelChange(newModel);
diff --git a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/model-panel.tsx b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/model-panel.tsx
index 7c0c9216..0d290331 100644
--- a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/model-panel.tsx
+++ b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/model-panel.tsx
@@ -11,10 +11,6 @@ interface IProps {
onModelSelect: (model: string) => void; // eslint-disable-line no-unused-vars
}
-/**
- * ModelPanel Component
- * Right panel showing models for the selected provider
- */
export const ModelPanel: FC<IProps> = ({ models, currentModel, providerIndex, onModelSelect }) => (
<div
className="absolute left-[240px] z-50 w-[300px] max-h-[500px] overflow-y-auto bg-slate-100 rounded-md shadow-xl"
diff --git a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/provider-icon.tsx b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/provider-icon.tsx
index d47cc0c3..7eb2f71f 100644
--- a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/provider-icon.tsx
+++ b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/provider-icon.tsx
@@ -2,21 +2,11 @@ import { FC, useState } from 'react';
import { cn } from '@react/shared/utils/general';
-/**
- * Props for ProviderIcon component
- */
interface IProps {
provider: string;
className?: string;
}
-/**
- * ProviderIcon Component
- * Displays provider logo with gradient "AI" badge fallback if image fails to load
- *
- * @param provider - Provider name to load icon for
- * @param className - Optional CSS classes for customization
- */
export const ProviderIcon: FC<IProps> = ({ provider, className = 'size-5 rounded-full' }) => {
const [hasError, setHasError] = useState<boolean>(false);
diff --git a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/provider-panel.tsx b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/provider-panel.tsx
index 6ba1a577..c4d71bce 100644
--- a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/provider-panel.tsx
+++ b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/provider-panel.tsx
@@ -11,10 +11,6 @@ interface IProps {
onProviderSelect: (provider: string) => void; // eslint-disable-line no-unused-vars
}
-/**
- * ProviderPanel Component
- * Left panel showing list of LLM providers
- */
export const ProviderPanel: FC<IProps> = ({ providers, selectedProvider, onProviderSelect }) => (
<div className="absolute top-full -left-3 z-50 mt-1 bg-slate-100 rounded-md shadow-xl border-t border-slate-200 min-w-[250px] max-h-[500px] overflow-y-auto divide-y divide-slate-200">
{providers.map((llmProvider, index) => (
diff --git a/packages/app/src/react/features/ai-chat/contexts/index.tsx b/packages/app/src/react/features/ai-chat/contexts/index.tsx
index 124d1a44..4df27072 100644
--- a/packages/app/src/react/features/ai-chat/contexts/index.tsx
+++ b/packages/app/src/react/features/ai-chat/contexts/index.tsx
@@ -23,16 +23,9 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {
const navigate = useNavigate();
- // Internal ref for tracking initialization state
const hasInitializedChatRef = useRef(false);
-
- // Model override state (temporary, not saved to agent config)
const [modelOverride, setModelOverride] = useState<string | null>(null);
- // ============================================================================
- // API HOOKS
- // ============================================================================
-
const { data: agent, isLoading: isAgentLoading } = useAgent(agentId, {
refetchOnWindowFocus: false,
refetchOnReconnect: false,
@@ -46,25 +39,13 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {
const agentSettings = settingsData?.settings;
- // ============================================================================
- // FILE UPLOAD MANAGEMENT
- // ============================================================================
-
const fileUpload = useFileUpload({
agentId: agentId || '',
chatId: agentSettings?.lastConversationId || '',
});
- // ============================================================================
- // SCROLL BEHAVIOR
- // ============================================================================
-
const scroll = useScrollToBottom(containerRef);
- // ============================================================================
- // CHAT STATE MANAGEMENT
- // ============================================================================
-
const chatStateV2 = useChatState({
agentId: agentId || '',
chatId: agentSettings?.lastConversationId || '',
@@ -73,7 +54,6 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {
inputRef,
});
- // Destructure for easier access
const {
messages,
setMessages,
@@ -83,20 +63,11 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {
retryLastMessage,
} = chatStateV2;
- // ============================================================================
- // CHAT ACTIONS
- // ============================================================================
-
- /**
- * Sends a message with optional file attachments
- * Integrates with the file upload system
- */
const sendMessage = useCallback(
async (message: string) => {
if (!message.trim() && fileUpload.attachments.length === 0) return;
try {
- // Convert V2 attachments to IAttachment format
const attachments = fileUpload.attachments.map((f) => ({
name: f.name,
type: f.type,
@@ -107,8 +78,6 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {
}));
await sendMessageV2(message, attachments);
-
- // Clear files after successful send
fileUpload.clear();
} catch (error) {
console.error('Failed to send message:', error); // eslint-disable-line no-console
@@ -117,9 +86,6 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {
[fileUpload, sendMessageV2],
);
- /**
- * Creates a new chat session/conversation
- */
const createSession = useCallback(async () => {
try {
const conversation = await createChat({
@@ -141,60 +107,39 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {
}
}, [agentId, createChat, updateAgentSettings]);
- /**
- * Clears current chat session and creates a new one
- */
const resetSession = useCallback(async () => {
stopStreaming();
setMessages([]);
fileUpload.clear();
await createSession();
- // Trigger callback
inputRef?.current?.focus();
- // Track observability events
Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);
Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);
}, [createSession, setMessages, fileUpload, stopStreaming, inputRef]);
- // ============================================================================
- // LIFECYCLE EFFECTS
- // ============================================================================
-
- /**
- * Initialize chat session on component mount
- * Only runs once when both agent and settings are loaded
- */
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;
createSession().then(() => inputRef?.current?.focus());
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [agentSettings, agent, agentId]); // Only depend on core values, not callbacks
+ }, [agentSettings, agent, agentId]);
- /**
- * Track chat session lifecycle for observability
- */
useEffect(() => {
Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);
return () => Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);
}, []);
- /**
- * Auto-focus input when agent is loaded and not disabled
- */
useEffect(() => {
const inputDisabled = isChatCreating || isAgentLoading || isStreaming;
if (!isAgentLoading && !inputDisabled) inputRef.current?.focus();
}, [isAgentLoading, isChatCreating, isStreaming]);
- // Memoize the store to avoid unnecessary re-renders
const values: IChatContext = useMemo(
() => ({
ref: { input: inputRef, container: containerRef },
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-attachments.ts b/packages/app/src/react/features/ai-chat/hooks/use-attachments.ts
deleted file mode 100644
index 7a9d3824..00000000
--- a/packages/app/src/react/features/ai-chat/hooks/use-attachments.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
-
-import { ChatAPIClient } from '@react/features/ai-chat/clients/chat-api.client';
-import { IMessageFile } from '@react/features/ai-chat/types/chat.types';
-import {
- createFileMetadata,
- deleteFile,
- FILE_LIMITS,
- generateUniqueFileId,
- validateSingleFile,
-} from '@react/features/ai-chat/utils/file';
-
-interface IProps {
- agentId?: string;
- chatId?: string;
-}
-
-export const useAttachments = (props: IProps) => {
- const { agentId, chatId } = props || {};
-
- const [files, setFiles] = useState<IMessageFile[]>([]);
- const [uploadingIds, setUploadingIds] = useState<Set<string>>(new Set());
- const [errorMessage, setErrorMessage] = useState('');
-
- const isLoading = uploadingIds.size > 0;
-
- // Create ChatAPIClient instance for file uploads (memoized to avoid recreating)
- const chatClient = useMemo(() => new ChatAPIClient(), []);
-
- // Auto-clear upload error after 5 seconds when it becomes visible
- useEffect(() => {
- let timeoutId: NodeJS.Timeout;
- if (errorMessage) {
- timeoutId = setTimeout(() => setErrorMessage(''), 5000);
- }
- return () => {
- if (timeoutId) clearTimeout(timeoutId);
- };
- }, [errorMessage]);
-
- const addFiles = useCallback(
- async (newFiles: File[]) => {
- if (newFiles.length === 0) return;
- const remainingSlots = FILE_LIMITS.MAX_ATTACHED_FILES - files.length;
-
- if (remainingSlots <= 0) {
- setErrorMessage(`Maximum ${FILE_LIMITS.MAX_ATTACHED_FILES} files allowed`);
- return;
- }
-
- const validatedFiles = newFiles.map((file) => ({
- file,
- error: validateSingleFile(file),
- id: generateUniqueFileId(file),
- }));
-
- const validFiles = validatedFiles.filter((item) => !item.error);
- const invalidFiles = validatedFiles.filter((item) => item.error);
-
- // Always surface an error if any invalid files were included
- if (invalidFiles.length > 0) {
- setErrorMessage(invalidFiles[0].error || 'Failed to upload file');
- }
-
- if (validFiles.length > 0) {
- const filesToUpload = validFiles.slice(0, remainingSlots);
-
- if (validFiles.length > remainingSlots) {
- setErrorMessage(
- `You can only attach ${FILE_LIMITS.MAX_ATTACHED_FILES} files. Extra files were ignored.`,
- );
- }
-
- // Add files to uploadingIds set using unique IDs
- const newFileIds = new Set(filesToUpload.map((f) => f.id));
- setUploadingIds((prev) => new Set([...prev, ...newFileIds]));
-
- // Add files to state with metadata and unique IDs
- setFiles((prevFiles) => [
- ...prevFiles,
- ...filesToUpload.map(({ file, id }) => ({
- ...createFileMetadata(file),
- id, // Add unique ID to file metadata
- })),
- ]);
-
- // Upload files concurrently using ChatAPIClient
- const uploadPromises = filesToUpload.map(async ({ file, id }) => {
- try {
- const attachment = await chatClient.uploadFile(file, agentId, chatId);
-
- setFiles((prevFiles) =>
- prevFiles.map((f) =>
- f.id === id
- ? {
- ...f,
- url: attachment.url,
- name: attachment.name,
- type: attachment.type,
- size: attachment.size,
- metadata: {
- ...f.metadata,
- // Do not set key for runtime uploads (avoid delete attempts)
- publicUrl: attachment.url,
- fileType: attachment.type,
- isUploading: false,
- },
- }
- : f,
- ),
- );
- } catch (error) {
- setFiles((prevFiles) => prevFiles.filter((f) => f.id !== id));
- setErrorMessage(error instanceof Error ? error.message : 'Failed to upload file');
- } finally {
- setUploadingIds((prev) => {
- const next = new Set(prev);
- next.delete(id);
- return next;
- });
- }
- });
-
- await Promise.all(uploadPromises);
- }
- },
- [files.length, agentId, chatId, chatClient],
- );
-
- const removeFile = useCallback(
- async (index: number) => {
- const fileToRemove = files[index];
- setFiles((prevFiles) => prevFiles.filter((_, i) => i !== index));
- if (fileToRemove.metadata.key) await deleteFile(fileToRemove.metadata.key);
- },
- [files],
- );
-
- const clearError = useCallback(() => setErrorMessage(''), []);
- const clearFiles = useCallback(() => setFiles([]), []);
- const clearAll = useCallback(() => {
- setFiles([]);
- setErrorMessage('');
- setUploadingIds(new Set());
- }, []);
-
- return {
- data: files,
- isLoading,
- uploadingIds,
- errorMessage,
-
- addFiles,
- removeFile,
- clearError,
- clearFiles,
- clearAll,
- };
-};
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-stream.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-stream.ts
deleted file mode 100644
index 310cc0ac..00000000
--- a/packages/app/src/react/features/ai-chat/hooks/use-chat-stream.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-/**
- * React hook for managing chat streaming with abort control
- * Provides clean interface for streaming chat responses with lifecycle management
- */
-
-import { ChatAPIClient } from '@react/features/ai-chat/clients/chat-api.client';
-import {
- IChatError,
- IStreamCallbacks,
- IStreamConfig,
-} from '@react/features/ai-chat/types/chat.types';
-import { useCallback, useRef, useState } from 'react';
-
-/**
- * Hook configuration interface
- */
-interface IUseChatStreamConfig {
- onStreamStart?: () => void; // Called when stream starts
- onStreamEnd?: () => void; // Called when stream completes
-}
-
-/**
- * Hook return interface
- */
-interface IUseChatStreamReturn {
- isStreaming: boolean; // Whether a stream is currently active
- startStream: (config: IStreamConfig, callbacks: IStreamCallbacks) => Promise<void>; // eslint-disable-line no-unused-vars
- abortStream: () => void; // Abort the current stream
-}
-
-/**
- * Custom hook for managing chat streaming with abort control
- * Handles stream lifecycle, abort signals, and error states
- *
- * @param config - Hook configuration
- * @returns Stream state and control functions
- *
- * @example
- * ```typescript
- * const { isStreaming, startStream, abortStream } = useChatStream({
- * onStreamStart: () => console.log('Stream started'),
- * onStreamEnd: () => console.log('Stream ended'),
- * });
- *
- * // Start streaming
- * await startStream(
- * {
- * agentId: 'agent-123',
- * chatId: 'chat-456',
- * message: 'Hello!',
- * signal: abortController.signal,
- * },
- * {
- * onContent: (content) => console.log(content),
- * onError: (error) => console.error(error),
- * onComplete: () => console.log('Done'),
- * }
- * );
- *
- * // Abort streaming
- * abortStream();
- * ```
- */
-export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStreamReturn => {
- const { onStreamStart, onStreamEnd } = config;
-
- // State management
- const [isStreaming, setIsStreaming] = useState(false);
-
- // Refs for lifecycle management
- const abortControllerRef = useRef<AbortController | null>(null);
- const apiClient = new ChatAPIClient();
-
- /**
- * Starts a new chat stream
- * Automatically manages abort controller and lifecycle callbacks
- */
- const startStream = useCallback(
- async (streamConfig: IStreamConfig, callbacks: IStreamCallbacks): Promise<void> => {
- // Abort any existing stream
- if (abortControllerRef.current) {
- abortControllerRef.current.abort();
- }
-
- // Create new abort controller
- const abortController = new AbortController();
- abortControllerRef.current = abortController;
-
- // Set streaming state
- setIsStreaming(true);
-
- // Notify start
- if (onStreamStart) onStreamStart();
-
- try {
- // Wrap callbacks to manage lifecycle
- const wrappedCallbacks: IStreamCallbacks = {
- ...callbacks,
- onError: (streamError) => callbacks.onError(streamError),
- onComplete: () => {
- setIsStreaming(false);
- abortControllerRef.current = null;
-
- if (onStreamEnd) onStreamEnd();
-
- callbacks.onComplete();
- },
- };
-
- // Start streaming with abort signal
- await apiClient.streamChat(
- { ...streamConfig, signal: abortController.signal },
- wrappedCallbacks,
- );
- } catch (streamError) {
- // Handle errors
- const chatError = streamError as IChatError;
- setIsStreaming(false);
- abortControllerRef.current = null;
-
- if (onStreamEnd) onStreamEnd();
-
- throw chatError;
- }
- },
- [onStreamStart, onStreamEnd], // eslint-disable-line react-hooks/exhaustive-deps
- );
-
- /**
- * Aborts the current stream
- * Safe to call even if no stream is active
- */
- const abortStream = useCallback(() => {
- if (abortControllerRef.current) {
- abortControllerRef.current.abort();
- abortControllerRef.current = null;
- setIsStreaming(false);
-
- if (onStreamEnd) onStreamEnd();
- }
- }, [onStreamEnd]);
-
- return { isStreaming, startStream, abortStream };
-};
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.ts
deleted file mode 100644
index 6d3d125f..00000000
--- a/packages/app/src/react/features/ai-chat/hooks/use-chat.ts
+++ /dev/null
@@ -1,492 +0,0 @@
-/* eslint-disable no-unused-vars */
-
-/**
- * Professional React hook for complete chat state management
- * Combines streaming, message history, file uploads, and error handling
- */
-
-import { USER_STOPPED_MESSAGE } from '@react/features/ai-chat/constants';
-import { useChatStream } from '@react/features/ai-chat/hooks';
-import {
- IChatMessage,
- IMessageFile,
- IMetaMessages,
- IUseChatReturn,
-} from '@react/features/ai-chat/types/chat.types';
-import { useCallback, useRef, useState } from 'react';
-
-/**
- * Hook configuration interface
- */
-interface IUseChatConfig {
- agentId: string;
- chatId: string; // Chat/Conversation ID
- modelId?: string; // Model ID to override backend model selection
- headers?: Record<string, string>; // Custom headers for requests
- onChatComplete?: (message: string) => void; // Called when chat completes successfully
- onError?: (error: Error) => void; // Called when error occurs
-}
-
-/**
- * Main chat hook for complete state management
- * Provides all functionality needed for a chat interface
- *
- * @param config - Hook configuration
- * @returns Complete chat state and actions
- *
- * @example
- * ```typescript
- * const {
- * messages,
- * isGenerating,
- * sendMessage,
- * retryMessage,
- * stopGenerating,
- * clearMessages,
- * } = useChat({
- * agentId: 'agent-123',
- * chatId: 'chat-456',
- * avatar: '/avatar.png',
- * });
- *
- * // Send a message
- * await sendMessage('Hello, AI!');
- *
- * // Send with files
- * await sendMessage('Analyze these files', [file1, file2]);
- *
- * // Retry last message
- * await retryMessage();
- *
- * // Stop generation
- * stopGenerating();
- * ```
- */
-export const useChat = (config: IUseChatConfig): IUseChatReturn => {
- const { agentId, chatId, modelId, headers, onChatComplete, onError } = config;
-
- // State management
- const [messages, setMessages] = useState<IChatMessage[]>([]);
- const [isProcessing, setIsProcessing] = useState(false);
-
- const lastUserMessageRef = useRef<{ message: string; files?: IMessageFile[] } | null>(null);
-
- // Current AI message being constructed
- const currentAIMessageRef = useRef<string>('');
-
- // Track if we're in thinking state to create new message after
- const isThinkingRef = useRef<boolean>(false);
-
- // Track current conversation turn ID for grouping messages
- const currentTurnIdRef = useRef<string | null>(null);
-
- // Throttling ref for batched updates
- const updateThrottleRef = useRef<NodeJS.Timeout | null>(null);
- const pendingUpdateRef = useRef<{ content: string; turnId?: string } | null>(null);
-
- // Stream management
- const { isStreaming, startStream, abortStream } = useChatStream({
- onStreamStart: () => {
- currentAIMessageRef.current = '';
- isThinkingRef.current = false;
- },
- onStreamEnd: () => setIsProcessing(false),
- });
-
- /**
- * Adds a user message to the chat
- */
- const addUserMessage = useCallback((message: string, files?: IMessageFile[]) => {
- const userMessage: IChatMessage = {
- id: Date.now(),
- message,
- type: 'user', // Type determines user vs system - no me property needed!
- timestamp: Date.now(),
- files: files || [],
- };
-
- setMessages((prev) => [...prev, userMessage]);
- }, []);
-
- /**
- * Add or update AI message (similar to addMetaMessage pattern)
- * If last message is 'loading' or 'system', updates it; otherwise adds new message
- * @param content - Message content (empty string for new loading message)
- * @param turnId - Optional conversation turn ID
- */
- const handleAIMessage = useCallback((content: string = '', turnId?: string) => {
- setMessages((prev) => {
- const lastMessage = prev[prev.length - 1];
-
- // If last message is loading or system type, update it instead of adding new
- if (lastMessage && (lastMessage.type === 'system' || lastMessage.type === 'loading')) {
- // Optimized: Create new array only with modified last element
- // This avoids copying the entire array for long conversations
- const newMessages = prev.slice(0, -1);
- newMessages.push({
- ...lastMessage,
- message: content,
- turnId: turnId || lastMessage.turnId,
- type: content ? 'system' : 'loading',
- });
- return newMessages;
- }
-
- // Otherwise, add new AI message
- const aiMessage: IChatMessage = {
- id: Date.now() + 1,
- message: content,
- type: content ? 'system' : 'loading',
- timestamp: Date.now(),
- turnId: turnId || currentTurnIdRef.current || undefined,
- };
-
- return [...prev, aiMessage];
- });
- }, []);
-
- /**
- * Throttled update for message content during streaming
- * Batches multiple chunk updates to reduce re-renders
- * @param content - Accumulated content
- * @param turnId - Optional conversation turn ID
- */
- const updateStreamingMessage = useCallback((content: string, turnId?: string) => {
- // Store pending update
- pendingUpdateRef.current = { content, turnId };
-
- // Clear existing throttle
- if (updateThrottleRef.current) {
- clearTimeout(updateThrottleRef.current);
- }
-
- // Schedule batched update
- updateThrottleRef.current = setTimeout(() => {
- if (pendingUpdateRef.current) {
- const { content: pendingContent, turnId } = pendingUpdateRef.current;
-
- setMessages((prev) => {
- const lastMessageIndex = prev.length - 1;
-
- if (lastMessageIndex >= 0) {
- const lastMsg = prev[lastMessageIndex];
- const needsUpdate =
- lastMsg.type === 'system' ||
- lastMsg.type === 'loading' ||
- (turnId && !lastMsg.turnId);
-
- if (needsUpdate) {
- // Optimized: Only update last element
- const newMessages = prev.slice(0, -1);
- newMessages.push({
- ...lastMsg,
- message: pendingContent,
- turnId: turnId || lastMsg.turnId,
- type: 'system',
- });
- return newMessages;
- }
- }
-
- return prev;
- });
-
- pendingUpdateRef.current = null;
- }
- updateThrottleRef.current = null;
- }, 16); // 16ms throttle (60fps) - ultra-smooth, matches scroll rate
- }, []);
-
- /**
- * Add and update meta messages for current AI response
- */
- const addMetaMessage = useCallback((metaMessages: IMetaMessages) => {
- if (!metaMessages || !metaMessages.title) return;
-
- setMessages((prev) => {
- const lastMessage = prev[prev.length - 1];
-
- // If last message is loading or thinking type, update it instead of adding new
- if (lastMessage?.type === 'loading' || lastMessage?.type === 'meta') {
- return prev.map((msg, index) =>
- index === prev.length - 1
- ? {
- ...msg,
- type: 'thinking',
- message: metaMessages.title,
- metaMessages, // Store full metaMessages object for component
- timestamp: Date.now(),
- }
- : msg,
- );
- }
-
- // Otherwise, add new loading message
- const metaMessage: IChatMessage = {
- id: Date.now() + 2,
- type: 'thinking',
- message: metaMessages.title,
- timestamp: Date.now(),
- metaMessages, // Store full metaMessages object for component
- turnId: currentTurnIdRef.current || undefined,
- };
-
- return [...prev, metaMessage];
- });
- }, []);
-
- /**
- * Sends a message to the AI
- * Accepts either raw File[] or FileWithMetadata[] (already uploaded)
- */
- const sendMessage = useCallback(
- async (message: string, files?: IMessageFile[]): Promise<void> => {
- // Validate input
- if (!message.trim() && (!files || files.length === 0)) return;
-
- // Store for retry
- lastUserMessageRef.current = { message, files };
-
- try {
- setIsProcessing(true);
-
- // Add user message to UI
- addUserMessage(message, files);
-
- // Add empty AI message for streaming
- handleAIMessage();
-
- // Start streaming
- await startStream(
- {
- agentId,
- chatId,
- message,
- modelId, // Pass model ID to override backend model selection
- attachments: files ?? [],
- signal: new AbortController().signal, // Signal managed by useChatStream
- headers,
- },
- {
- onStart: () => {
- currentTurnIdRef.current = null; // Reset turn ID for new conversation turn
- },
- onContent: (content: string, turnId?: string) => {
- // Capture turn ID only once
- if (turnId && !currentTurnIdRef.current) {
- currentTurnIdRef.current = turnId;
- }
-
- // If content comes after thinking, replace thinking message with loading message
- if (isThinkingRef.current) {
- setMessages((prev) => {
- const lastMessageIndex = prev.length - 1;
- if (lastMessageIndex >= 0 && prev[lastMessageIndex].type === 'meta') {
- // Replace thinking message with loading message
- const newMessages = prev.slice(0, -1);
- newMessages.push({
- ...prev[lastMessageIndex],
- type: 'loading',
- message: '',
- turnId: turnId || prev[lastMessageIndex].turnId,
- });
- return newMessages;
- }
- return prev;
- });
- isThinkingRef.current = false; // Mark that we've handled the thinking transition
- currentAIMessageRef.current = ''; // Reset accumulator for new message
- }
-
- // Accumulate content
- currentAIMessageRef.current += content;
-
- // Use throttled update for better performance during streaming
- // This batches rapid chunk updates to reduce re-renders
- updateStreamingMessage(currentAIMessageRef.current, turnId);
- },
- onMetaMessages: (metaMessages: IMetaMessages, turnId?: string) => {
- if (turnId && !currentTurnIdRef.current) {
- currentTurnIdRef.current = turnId; // Capture turn ID from thinking messages
- }
-
- // Mark that we're in thinking state
- isThinkingRef.current = true;
-
- addMetaMessage(metaMessages);
- },
-
- onError: (streamError) => {
- // Handle stream errors
- if (streamError.isAborted) {
- // 🎯 User stopped generation
- const currentContent = currentAIMessageRef.current;
-
- // Step 1: Finalize the AI message (loading → system)
- setMessages((prev) => {
- const updated = [...prev];
- const lastMessageIndex = updated.length - 1;
-
- if (lastMessageIndex >= 0) {
- const lastMsg = updated[lastMessageIndex];
- if (lastMsg.type === 'loading' || lastMsg.type === 'system') {
- updated[lastMessageIndex] = {
- ...lastMsg,
- message: currentContent || lastMsg.message,
- type: 'system',
- };
- }
- }
-
- // Step 2: Add separate error message
- const stopMessage: IChatMessage = {
- id: Date.now() + 2,
- message: USER_STOPPED_MESSAGE,
- type: 'error', // Show as error/warning style but not an actual error
- timestamp: Date.now(),
- turnId: currentTurnIdRef.current || undefined,
- };
-
- updated.push(stopMessage);
-
- return updated;
- });
- } else {
- // Real error - show error message
- handleAIMessage(streamError.message);
- }
-
- // Reset state
- currentAIMessageRef.current = '';
- currentTurnIdRef.current = null;
-
- if (onError) onError(new Error(streamError.message));
- },
- onComplete: () => {
- // Clear throttle and flush pending updates immediately
- if (updateThrottleRef.current) {
- clearTimeout(updateThrottleRef.current);
- updateThrottleRef.current = null;
- }
-
- // Finalize message with accumulated content
- const finalMessage = currentAIMessageRef.current;
- handleAIMessage(finalMessage); // immediate update
-
- // Reset state
- currentAIMessageRef.current = '';
- currentTurnIdRef.current = null;
- pendingUpdateRef.current = null;
-
- if (onChatComplete) onChatComplete(finalMessage);
- },
- },
- );
- } catch (sendError) {
- const errorMessage =
- sendError instanceof Error ? sendError.message : 'Failed to send message';
-
- if (onError) onError(sendError instanceof Error ? sendError : new Error(errorMessage));
- } finally {
- setIsProcessing(false);
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [
- agentId,
- chatId,
- headers,
- addUserMessage,
- handleAIMessage,
- addMetaMessage,
- updateStreamingMessage,
- startStream,
- onChatComplete,
- onError,
- ],
- );
-
- /**
- * Retries the last sent message
- */
- const retryLastMessage = useCallback(async (): Promise<void> => {
- if (!lastUserMessageRef.current) return;
-
- const { message, files } = lastUserMessageRef.current;
-
- // Smart removal: find last user message index and remove everything from that point
- setMessages((prev) => {
- // Find the index of the last user message
- let lastUserMessageIndex = -1;
- for (let i = prev.length - 1; i >= 0; i--) {
- if (prev[i].type === 'user') {
- lastUserMessageIndex = i;
- break;
- }
- }
-
- // If no user message found, don't remove anything
- if (lastUserMessageIndex === -1) return prev;
-
- // Remove everything from the last user message onwards
- return prev.slice(0, lastUserMessageIndex);
- });
-
- // Resend the message
- await sendMessage(message, files);
- }, [sendMessage]);
-
- /**
- * Stops the current generation
- * The error handler will preserve generated content and append USER_STOPPED_MESSAGE
- */
- const stopGenerating = useCallback(() => {
- // Step 1: Clear throttle timeout
- if (updateThrottleRef.current) {
- clearTimeout(updateThrottleRef.current);
- updateThrottleRef.current = null;
- }
-
- // Step 2: Flush any pending updates before aborting
- if (pendingUpdateRef.current) {
- const { content: pendingContent } = pendingUpdateRef.current;
- currentAIMessageRef.current = pendingContent; // Save pending content
- pendingUpdateRef.current = null;
- }
-
- // Step 3: Abort the stream (onError will handle the rest)
- abortStream();
- }, [abortStream]);
-
- /**
- * Clears all messages and resets state
- */
- const clearMessages = useCallback(() => {
- // Clear throttle timeout
- if (updateThrottleRef.current) {
- clearTimeout(updateThrottleRef.current);
- updateThrottleRef.current = null;
- }
-
- // Clear pending updates
- pendingUpdateRef.current = null;
-
- // Clear messages and refs
- setMessages([]);
- lastUserMessageRef.current = null;
- currentAIMessageRef.current = '';
- currentTurnIdRef.current = null;
- }, []);
-
- return {
- // State
- messages,
- isStreaming,
-
- // Actions
- sendMessage,
- clearMessages,
- retryMessage: retryLastMessage,
- stopStreaming: stopGenerating,
- };
-};
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.ts
index f2ad8e17..e8ec22f9 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,15 +1,8 @@
import { RefObject, useCallback, useEffect, useRef } from 'react';
-interface UseDragAndDropProps {
- onDrop: (files: File[]) => Promise<void>; // eslint-disable-line no-unused-vars
-}
+type IProps = { onDrop: (files: File[]) => Promise<void> }; // eslint-disable-line no-unused-vars
-/**
- * A hook that provides drag and drop functionality for files within a specific container
- * @param onDrop - Callback function that handles the dropped files
- * @returns A ref object to be attached to the container element where drag and drop should be enabled
- */
-export const useDragAndDrop = ({ onDrop }: UseDragAndDropProps): RefObject<HTMLElement> => {
+export const useDragAndDrop = ({ onDrop }: IProps): RefObject<HTMLElement> => {
const containerRef = useRef<HTMLElement>(null);
const dragCounterRef = useRef(0);
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-file-upload.ts b/packages/app/src/react/features/ai-chat/hooks/use-file-upload.ts
index 3e255d2f..a854f23a 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-file-upload.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-file-upload.ts
@@ -11,44 +11,14 @@ import {
} from '@react/features/ai-chat/utils/file';
import { useCallback, useEffect, useRef, useState } from 'react';
-/**
- * File upload hook options
- */
-interface IFileUploadOptions {
+type IProps = {
agentId?: string;
chatId?: string;
-}
-
-/**
- * Custom hook for managing file uploads with preview support
- *
- * @param options - Hook configuration with agentId and chatId
- * @returns File upload state and methods
- *
- * @example
- * ```typescript
- * const {
- * attachments,
- * uploading,
- * process,
- * remove,
- * clear,
- * } = useFileUpload({ agentId: 'agent-123', chatId: 'chat-456' });
- *
- * // Process files from input
- * await process(fileList);
- *
- * // Remove single file
- * remove(0);
- *
- * // Clear all
- * clear();
- * ```
- */
-export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
+};
+
+export const useFileUpload = (options: IProps): IFileUpload => {
const { agentId, chatId } = options;
- // State
const [attachments, setAttachments] = useState<IFileAttachment[]>([]);
const [status, setStatus] = useState<Record<string, IUploadStatus>>({});
const [uploading, setUploading] = useState(false);
@@ -56,11 +26,9 @@ export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
const [toast, setToast] = useState('');
const [showToast, setShowToast] = useState(false);
- // Refs
const blobsRef = useRef<Set<string>>(new Set());
const inputRef = useRef<HTMLInputElement>(null);
- // Auto-hide error message after 5 seconds
useEffect(() => {
let timer: ReturnType<typeof setTimeout>;
if (errorMessage) {
@@ -71,7 +39,6 @@ export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
};
}, [errorMessage]);
- // Handle upload error
const onError = useCallback(
(fileName: string, message: string) => {
setErrorMessage(message);
@@ -96,7 +63,6 @@ export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
[attachments],
);
- // Process files for upload
const processFiles = useCallback(
async (files: File[]) => {
if (files.length === 0) return;
@@ -124,7 +90,6 @@ export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
if (valid.length > 0) {
const pending = valid.slice(0, slots);
- // Create attachments with blob URLs for images
const created: IFileAttachment[] = pending.map(({ file, id }) => {
let blobUrl: string | null = null;
if (file.type.startsWith('image/')) {
@@ -189,7 +154,6 @@ export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
[attachments.length, agentId, chatId, onError],
);
- // Handle file input change
const onSelect = useCallback(
async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []).slice(0, MAX_UPLOADS);
@@ -198,7 +162,6 @@ export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
[processFiles],
);
- // Remove attachment by index
const remove = useCallback(
(index: number) => {
const target = attachments[index];
@@ -216,7 +179,6 @@ export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
[attachments],
);
- // Clear all attachments
const clear = useCallback(
(preserveBlobUrls = false) => {
if (preserveBlobUrls) {
@@ -239,7 +201,6 @@ export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
[attachments],
);
- // Cleanup unused blob URLs
const cleanup = useCallback(() => {
const active = new Set<string>();
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-scroll.ts b/packages/app/src/react/features/ai-chat/hooks/use-scroll.ts
index 420d8b3d..d5d28442 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-scroll.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-scroll.ts
@@ -6,11 +6,8 @@ export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {
const [showScrollButton, setShowScrollButton] = useState(false);
const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
- // Initialize scroll manager with container
useEffect(() => {
- if (ref.current) {
- scrollManager.init(ref.current);
- }
+ if (ref.current) scrollManager.init(ref.current);
}, [ref]);
const handleScroll = useCallback(() => {
@@ -20,23 +17,12 @@ export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {
if (ref.current) {
const { scrollTop, scrollHeight, clientHeight } = ref.current;
- /**
- * 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 threshold = 200;
const isScrolledUp = distanceFromBottom > threshold;
setShowScrollButton(isScrolledUp);
- // Update auto-scroll state based on scroll position
const isNearBottom = distanceFromBottom <= threshold;
setShouldAutoScroll(isNearBottom);
}
@@ -49,30 +35,15 @@ export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {
top: ref.current.scrollHeight,
behavior: smooth ? 'smooth' : 'auto',
});
- // When user manually scrolls to bottom, enable auto-scroll
setShouldAutoScroll(true);
}
},
[ref],
);
- /**
- * 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) => {
- // Don't check shouldAutoScroll here - let scroll manager handle it
- // This is critical for streaming behavior
- scrollManager.smartScrollToBottom({ behavior: smooth ? 'smooth' : 'auto', delay: 0 });
- },
- [], // Removed shouldAutoScroll dependency - scroll manager handles it internally
- );
+ const smartScrollToBottom = useCallback((smooth: boolean = true) => {
+ scrollManager.smartScrollToBottom({ behavior: smooth ? 'smooth' : 'auto', delay: 0 });
+ }, []);
useEffect(() => {
const container = ref.current;
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.tsx
index 76e653e0..21400c98 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
@@ -1,4 +1,4 @@
-import { ChatHeader, Chats, Container, Footer } from '@react/features/ai-chat/components';
+import { Chats, Container, Footer, Header } from '@react/features/ai-chat/components';
import { ChatContextProvider } from '@react/features/ai-chat/contexts';
import { memo } from 'react';
@@ -6,7 +6,7 @@ const AgentChatPage = () => {
return (
<ChatContextProvider>
<Container>
- <ChatHeader />
+ <Header />
<Chats />
<Footer />
</Container>