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 ChatAPIClient and related components for improved error handling and message structure
Salman-Ahamedd414182ea4f2
diff --git a/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts b/packages/app/src/react/features/ai-chat/clients/chat-api.client.tsindex 5f8c7a2e..8c2fff03 100644--- a/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts+++ b/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts@@ -77,22 +77,22 @@ export class ChatAPIClient {const { agentId, chatId, message, modelId, attachments, signal, headers = {} } = streamConfig;const { onContent, onMetaMessages, onError, onStart, onComplete } = callbacks;- // Validate required parameters- // Message can be empty if attachments are provided- if (!agentId || !chatId || (!message && (!attachments || attachments.length === 0))) {- const error: IChatError = {- message: 'Missing required parameters: agentId, chatId, or message',- type: 'system',- };- onError(error);- return Promise.reject(error);- }-// State management for stream processinglet accumulatedData = ''; // eslint-disable-line prefer-const- let reader: ReadableStreamDefaultReader<Uint8Array<ArrayBufferLike>>;+ let reader: ReadableStreamDefaultReader<Uint8Array<ArrayBufferLike>> | undefined;try {+ // Validate required parameters+ // Message can be empty if attachments are provided+ if (!agentId || !chatId || (!message && (!attachments || attachments.length === 0))) {+ const error: IChatError = {+ message: 'Missing required parameters: agentId, chatId, or message',+ type: 'system',+ };+ // Throw to be handled by catch block+ throw error;+ }+// Start performance monitoringperformanceMonitor.startStream();@@ -125,8 +125,8 @@ export class ChatAPIClient {message: errorData.message || `HTTP ${response.status}: Failed to get response`,type: 'network',};- onError(error);- return Promise.reject(error);+ // Don't call onError here - let the catch block handle it to avoid duplicate error handling+ throw error;}// Get stream reader@@ -136,15 +136,14 @@ export class ChatAPIClient {message: 'Failed to get response reader - response body is null',type: 'stream',};- onError(error);- return Promise.reject(error);+ // Don't call onError here - let the catch block handle it to avoid duplicate error handling+ throw error;}// Process streamawait this.processStream(reader, signal, accumulatedData, {onContent,onMetaMessages,- onError,});// End performance monitoring@@ -158,7 +157,7 @@ export class ChatAPIClient {// End performance monitoring on errorperformanceMonitor.endStream();- // Notify error callback+ // Notify error callback (single point of error notification)onError(chatError);// Clean up reader@@ -186,9 +185,9 @@ export class ChatAPIClient {reader: ReadableStreamDefaultReader<Uint8Array>,signal: AbortSignal,accumulatedData: string,- callbacks: Pick<IStreamCallbacks, 'onContent' | 'onMetaMessages' | 'onError'>,+ callbacks: Pick<IStreamCallbacks, 'onContent' | 'onMetaMessages'>,): Promise<void> {- const { onContent, onMetaMessages, onError } = callbacks;+ const { onContent, onMetaMessages } = callbacks;const decoder = new TextDecoder();while (true) {@@ -226,7 +225,7 @@ export class ChatAPIClient {// Process each chunkfor (const chunk of chunks) {- await this.processChunk(chunk, { onContent, onMetaMessages, onError });+ await this.processChunk(chunk, { onContent, onMetaMessages });}// Clear accumulated data after successful processing@@ -242,23 +241,22 @@ export class ChatAPIClient {*/private async processChunk(chunk: IStreamChunk,- callbacks: Pick<IStreamCallbacks, 'onContent' | 'onMetaMessages' | 'onError'>,+ callbacks: Pick<IStreamCallbacks, 'onContent' | 'onMetaMessages'>,): Promise<void> {- const { onContent, onMetaMessages, onError } = callbacks;+ const { onContent, onMetaMessages } = callbacks;const processed = processStreamChunk(chunk);// Extract conversation turn ID from chunkconst turnId = chunk.conversationTurnId;- // Handle errors+ // Handle errors - throw to stop stream processing, catch block will handle error notificationif (processed.hasError) {const error: IChatError = {type: 'stream',turnId, // Include turn ID in errormessage: processed.error || 'Unknown error occurred',};- onError(error);- return;+ throw error;}// Handle status messages (highest priority)diff --git a/packages/app/src/react/features/ai-chat/components/FileItemPreview.tsx b/packages/app/src/react/features/ai-chat/components/FileItemPreview.tsxnew file mode 100644index 00000000..b972c3c4--- /dev/null+++ b/packages/app/src/react/features/ai-chat/components/FileItemPreview.tsx@@ -0,0 +1,230 @@+import { cn } from '@src/react/shared/utils/general';+import { memo, useEffect, useMemo, useState, type FC, type ReactElement } from 'react';+import {+ FaRegFileAudio,+ FaRegFileCode,+ FaRegFileExcel,+ FaRegFileLines,+ FaRegFilePdf,+ FaRegFileVideo,+ FaRegFileWord,+ FaXmark,+} from 'react-icons/fa6';++const FILE_ICONS: Record<string, ReactElement> = {+ pdf: <FaRegFilePdf className="text-white text-xl" />,+ doc: <FaRegFileWord className="text-white text-xl" />,+ docx: <FaRegFileWord className="text-white text-xl" />,+ xls: <FaRegFileExcel className="text-white text-xl" />,+ xlsx: <FaRegFileExcel className="text-white text-xl" />,+ mp3: <FaRegFileAudio className="text-white text-xl" />,+ wav: <FaRegFileAudio className="text-white text-xl" />,+ ogg: <FaRegFileAudio className="text-white text-xl" />,+ mp4: <FaRegFileVideo className="text-white text-xl" />,+ avi: <FaRegFileVideo className="text-white text-xl" />,+ mov: <FaRegFileVideo className="text-white text-xl" />,+ js: <FaRegFileCode className="text-white text-xl" />,+ ts: <FaRegFileCode className="text-white text-xl" />,+ py: <FaRegFileCode className="text-white text-xl" />,+ java: <FaRegFileCode className="text-white text-xl" />,+ cpp: <FaRegFileCode className="text-white text-xl" />,+};++const DEFAULT_ICON = <FaRegFileLines className="text-white text-xl" />;++interface IRemoveButtonProps {+ onRemove: () => void;+}++const RemoveButton: FC<IRemoveButtonProps> = memo(({ onRemove }) => (+ <button+ onClick={onRemove}+ className="absolute -top-2 -right-2 size-6 flex justify-center items-center bg-white rounded-full text-[#6B7280] border border-[#E5E7EB] opacity-0 transition-opacity duration-200 z-10 cursor-pointer hover:text-[#374151] pt-0.5"+ aria-label="Remove file"+ >+ <FaXmark />+ </button>+));++RemoveButton.displayName = 'RemoveButton';++export interface IFileItemPreviewProps {+ fileObj?: File;+ url?: string;+ blobUrl?: string | null;+ mimeType?: string;+ fileName?: string;+ onRemove?: () => void;+ isUploading?: boolean;+ isReadOnly?: boolean;+ inChatBubble?: boolean;+}++const getFileExtension = (fileName?: string, url?: string, blobUrl?: string | null): string => {+ if (fileName) {+ return fileName.split('.').pop()?.toLowerCase() || '';+ }++ const urlToCheck = url || blobUrl;+ if (urlToCheck) {+ const urlPath = urlToCheck.split('/').pop() || urlToCheck.split('\\').pop() || '';+ const cleanPath = urlPath.split('?')[0];+ return cleanPath.split('.').pop()?.toLowerCase() || '';+ }++ return '';+};++const isImageType = (mimeType?: string): boolean => {+ return mimeType?.startsWith('image/') || false;+};++const getPreviewUrl = (+ fileObj?: File,+ url?: string,+ blobUrl?: string | null,+ inChatBubble?: boolean,+): string | null => {+ if (inChatBubble) {+ return blobUrl || url || null;+ }++ if (fileObj) {+ return URL.createObjectURL(fileObj);+ }++ return blobUrl || url || null;+};++export const FileItemPreview: FC<IFileItemPreviewProps> = memo(+ ({+ fileObj,+ url,+ blobUrl,+ mimeType,+ fileName,+ onRemove,+ isUploading = false,+ isReadOnly = false,+ inChatBubble = false,+ }) => {+ const [preview, setPreview] = useState<string | null>(() => {+ if (inChatBubble) return blobUrl || url || null;+ return null;+ });++ const fileExtension = useMemo(+ () => getFileExtension(fileName || fileObj?.name, url, blobUrl),+ [fileName, fileObj?.name, url, blobUrl],+ );++ const fileIcon = useMemo(() => FILE_ICONS[fileExtension] || DEFAULT_ICON, [fileExtension]);++ const isImage = useMemo(() => {+ const type = mimeType || fileObj?.type;+ return isImageType(type);+ }, [mimeType, fileObj?.type]);++ useEffect(() => {+ if (!isImage) {+ setPreview(null);+ return;+ }++ const previewUrl = getPreviewUrl(fileObj, url, blobUrl, inChatBubble);+ setPreview(previewUrl);++ return () => {+ if (previewUrl && !inChatBubble && fileObj) {+ URL.revokeObjectURL(previewUrl);+ }+ };+ }, [isImage, fileObj, url, blobUrl, inChatBubble]);++ const displayName = fileName || fileObj?.name || 'Unknown file';++ const handleImageError = () => {+ if (inChatBubble) {+ if (fileObj && isImageType(fileObj.type)) {+ try {+ const newBlobUrl = URL.createObjectURL(fileObj);+ setPreview(newBlobUrl);+ return;+ } catch {+ // Fall through to URL check+ }+ }++ if (url && (url.startsWith('http://') || url.startsWith('https://'))) {+ setPreview(url);+ } else setPreview(null);+ } else {+ if (url && preview !== url) setPreview(url);+ }+ };++ if (isImage) {+ return (+ <div+ className={cn(+ 'relative inline-block size-16 min-w-16 min-h-16 group',+ inChatBubble ? 'mt-0' : 'mt-4',+ )}+ >+ {preview ? (+ <img+ src={preview}+ alt={displayName}+ className="w-full h-full object-cover rounded-lg"+ onError={handleImageError}+ />+ ) : (+ <div className="w-full h-full bg-gray-200 rounded-lg flex flex-col items-center justify-center">+ <span className="text-xs text-gray-500">Preview unavailable</span>+ {inChatBubble && url && (+ <span className="text-[10px] text-gray-400 mt-1">{url.substring(0, 20)}...</span>+ )}+ </div>+ )}+ {isUploading && (+ <div className="absolute inset-0 bg-black/50 rounded-lg flex items-center justify-center">+ <div className="animate-spin rounded-full p-2 border-2 border-white border-t-transparent" />+ </div>+ )}+ {!isReadOnly && !inChatBubble && onRemove && (+ <div className="group-hover:[&>button]:opacity-100">+ <RemoveButton onRemove={onRemove} />+ </div>+ )}+ </div>+ );+ }++ return (+ <div className={cn('relative inline-block group', inChatBubble ? 'mt-0' : 'mt-4')}>+ {!isReadOnly && !inChatBubble && onRemove && (+ <div className="group-hover:[&>button]:opacity-100">+ <RemoveButton onRemove={onRemove} />+ </div>+ )}+ <div className="flex items-center gap-4 text-sm bg-white rounded-lg border border-[#E5E7EB] px-2 py-1 overflow-hidden w-40 min-w-32 max-h-[52px]">+ <div className="flex items-center justify-center bg-[#45C9A9] rounded-lg p-2 shrink-0">+ {isUploading ? (+ <div className="animate-spin rounded-full border-2 border-white border-t-transparent" />+ ) : (+ fileIcon+ )}+ </div>+ <div className="min-w-0 space-y-0.5">+ <h6 className="whitespace-nowrap overflow-hidden text-ellipsis font-semibold">+ {displayName}+ </h6>+ <p className="text-[#9CA3AF]">{fileExtension.toUpperCase() || 'FILE'}</p>+ </div>+ </div>+ </div>+ );+ },+);++FileItemPreview.displayName = 'FileItemPreview';diff --git a/packages/app/src/react/features/ai-chat/components/chat.tsx b/packages/app/src/react/features/ai-chat/components/chat.tsxindex b5961008..e93d919d 100644--- a/packages/app/src/react/features/ai-chat/components/chat.tsx+++ b/packages/app/src/react/features/ai-chat/components/chat.tsx@@ -7,12 +7,14 @@ import {ThinkingMessage,UserMessage,} from '@react/features/ai-chat/components';-import { IChatMessage } from '@react/features/ai-chat/types/chat.types';import '../styles/index.css';+import { IMessage } from '../types/chat';-interface IChatProps extends IChatMessage {- scrollToBottom?: () => void; // Callback to scroll chat to bottom+interface IChatProps extends IMessage {+ avatar: string;+ onRetryClick?: () => void;+ scrollToBottom?: () => void;}/**@@ -26,19 +28,19 @@ interface IChatProps extends IChatMessage {* @returns Appropriate message component*/export const Chat: FC<IChatProps> = memo((props) => {- const { type, files, avatar, message, metaMessages, onRetryClick, scrollToBottom } = props;+ const { type, attachments, avatar, content, metaMessages, onRetryClick, scrollToBottom } = props;switch (type) {case 'loading':return <ReplyLoader />;- case 'thinking':+ case 'meta':return <ThinkingMessage avatar={avatar} metaMessages={metaMessages} />;case 'user':- return <UserMessage message={message} files={files} />;+ return <UserMessage message={content} files={attachments} />;case 'system':- return <SystemMessage message={message} scrollToBottom={scrollToBottom} />;+ return <SystemMessage message={content} scrollToBottom={scrollToBottom} />;case 'error':- return <ErrorMessage message={message} onRetryClick={onRetryClick} />;+ return <ErrorMessage message={content} onRetryClick={onRetryClick} />;default:return <ErrorMessage message="Something went wrong!" onRetryClick={onRetryClick} />;}diff --git a/packages/app/src/react/features/ai-chat/components/chats.tsx b/packages/app/src/react/features/ai-chat/components/chats.tsxindex 29403fc5..b1201af9 100644--- a/packages/app/src/react/features/ai-chat/components/chats.tsx+++ b/packages/app/src/react/features/ai-chat/components/chats.tsx@@ -1,7 +1,6 @@-import { Chat, ChatsTurnGroup } from '@react/features/ai-chat/components';+import { Chat } from '@react/features/ai-chat/components';import { useChatStores, useDragAndDrop } from '@react/features/ai-chat/hooks';-import { IChatMessage } from '@react/features/ai-chat/types/chat.types';-import { FC, MutableRefObject, RefObject, useEffect, useMemo, useRef } from 'react';+import { FC, MutableRefObject, RefObject, useRef } from 'react';/*** Combines multiple refs into a single ref callback@@ -26,114 +25,16 @@ const combineRefs =export const Chats: FC = () => {const { ref: allRefs, agent: agentData, chat, files, scroll } = useChatStores() || {};- const { messages, isStreaming, retryMessage } = chat || {};- const { handleScroll, smartScrollToBottom, shouldAutoScroll } = scroll || {};+ const { messages, retryMessage } = chat || {};+ const { handleScroll, smartScrollToBottom } = scroll || {};const agent = agentData?.data;const containerRef = allRefs?.container;- const handleFileDrop = files.addFiles;+ const handleFileDrop = files.process;const ref = useRef<HTMLDivElement>(null);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);-- useEffect(() => {- const lastMessage = messages[messages.length - 1];- if (!lastMessage) return;-- const isSystemMessage = lastMessage.type === 'system';-- if (isSystemMessage) {- const messageLength = lastMessage.message?.length || 0;- const isNewMessage = lastMessage.id !== lastScrolledIdRef.current;- const contentGrew = messageLength > lastMessageLengthRef.current;-- if (isNewMessage || contentGrew) {- lastScrolledIdRef.current = lastMessage.id;- lastMessageLengthRef.current = messageLength;-- if (!shouldAutoScroll) return;-- const now = performance.now();- const timeSinceLastScroll = now - lastScrollTimeRef.current;- const shouldThrottle = !isNewMessage && timeSinceLastScroll < 16; // 60fps throttle-- if (rafRef.current !== null) {- cancelAnimationFrame(rafRef.current);- rafRef.current = null;- }-- const performScroll = () => {- lastScrollTimeRef.current = performance.now();-- if (containerRef?.current) {- containerRef.current.scrollTo({- top: containerRef.current.scrollHeight,- behavior: isStreaming ? 'auto' : 'smooth',- });- }- };-- if (shouldThrottle) {- rafRef.current = requestAnimationFrame(() => {- performScroll();- rafRef.current = null;- });- } else {- performScroll();- }- }- }-- return () => {- if (rafRef.current !== null) {- cancelAnimationFrame(rafRef.current);- rafRef.current = null;- }- };- }, [messages, isStreaming, containerRef, shouldAutoScroll]);-- const avatar = agent?.aiAgentSettings?.avatar;-- /**- * Group messages by turnId. Messages with same turnId are grouped together.- * User messages are always individual, AI messages with same turnId are grouped.- */- const groupedMessages = useMemo(() => {- const groups: Array<{- turnId: string | null;- messages: IChatMessage[];- isUserMessage: boolean;- }> = [];-- if (messages.length === 0) return groups;-- for (let i = 0; i < messages.length; i++) {- const message = messages[i];- const turnId = message.turnId || null;- const isUser = message.type === 'user';-- if (isUser) {- groups.push({ turnId, messages: [message], isUserMessage: true });- continue;- }-- const lastGroup = groups[groups.length - 1];-- if (lastGroup && !lastGroup.isUserMessage && lastGroup.turnId === turnId && turnId !== null) {- lastGroup.messages.push(message);- } else {- groups.push({ turnId, messages: [message], isUserMessage: false });- }- }-- return groups;- }, [messages]);-return (<divdata-chat-container@@ -146,48 +47,15 @@ export const Chats: FC = () => {onScroll={handleScroll}className="w-full h-full max-w-4xl flex-1 pb-10 space-y-3.5">- {groupedMessages.map((group, groupIndex) => {- const isLastGroup = groupIndex === groupedMessages.length - 1;- const lastMessageInGroup = group.messages[group.messages.length - 1];- const canRetry = lastMessageInGroup.type === 'error' && isLastGroup;- const onRetryClick = canRetry ? retryMessage : undefined;-- if (group.isUserMessage) {- const message = group.messages[0];-- return (- <Chat- key={message.id || groupIndex}- {...message}- avatar={avatar}- onRetryClick={onRetryClick}- scrollToBottom={smartScrollToBottom}- />- );- }-- if (group.turnId && group.messages.length > 0) {- return (- <ChatsTurnGroup- avatar={avatar}- key={group.turnId}- messages={group.messages}- onRetryClick={onRetryClick}- scrollToBottom={smartScrollToBottom}- />- );- }-- return group.messages.map((message, messageIndex) => (- <Chat- key={message.id || `${groupIndex}-${messageIndex}`}- {...message}- avatar={avatar}- scrollToBottom={smartScrollToBottom}- onRetryClick={messageIndex === group.messages.length - 1 ? onRetryClick : undefined}- />- ));- })}+ {messages.map((message, index) => (+ <Chat+ {...message}+ key={message.id}+ avatar={agent?.aiAgentSettings?.avatar}+ scrollToBottom={smartScrollToBottom}+ onRetryClick={index === messages.length - 1 ? retryMessage : undefined}+ />+ ))}</div></div>);diff --git a/packages/app/src/react/features/ai-chat/components/footer.tsx b/packages/app/src/react/features/ai-chat/components/footer.tsxindex 759091c3..e0fa8aad 100644--- a/packages/app/src/react/features/ai-chat/components/footer.tsx+++ b/packages/app/src/react/features/ai-chat/components/footer.tsx@@ -1,21 +1,23 @@import { ChatInput, ErrorToast, ScrollToBottomButton } from '@react/features/ai-chat/components';import { useChatStores } from '@react/features/ai-chat/hooks';-import { FC } from 'react';+import { FC, useCallback } 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 quotesexport const Footer: FC = () => {- const {- files: { errorMessage, clearError },- scroll: { showScrollButton, scrollToBottom },- } = useChatStores();+ const { files, scroll } = useChatStores();+ const { errorMessage, setErrorMessage } = files;+ const { showScrollButton, scrollToBottom } = scroll || {};++ const onClose = useCallback(() => setErrorMessage(''), [setErrorMessage]);+ const onScrollToBottom = useCallback(() => scrollToBottom(true), [scrollToBottom]);return (<div className="w-full max-w-4xl pt-2.5">- {errorMessage && <ErrorToast message={errorMessage} onClose={clearError} />}+ {errorMessage && <ErrorToast message={errorMessage} onClose={onClose} />}<div className="relative">- {showScrollButton && <ScrollToBottomButton onClick={() => scrollToBottom(true)} />}+ {showScrollButton && <ScrollToBottomButton onClick={onScrollToBottom} />}<ChatInput /></div>diff --git a/packages/app/src/react/features/ai-chat/components/input.tsx b/packages/app/src/react/features/ai-chat/components/input.tsxindex 05592e1f..e0950e8d 100644--- a/packages/app/src/react/features/ai-chat/components/input.tsx+++ b/packages/app/src/react/features/ai-chat/components/input.tsx@@ -9,7 +9,8 @@ import {} from 'react';import '../styles/index.css';-import { AttachmentButton, FileItemPreview, SendButton } from '@react/features/ai-chat/components';+import { AttachmentButton, SendButton } from '@react/features/ai-chat/components';+import { FileItemPreview } from '@react/features/ai-chat/components/FileItemPreview';import { CHAT_ACCEPTED_FILE_TYPES } from '@react/features/ai-chat/constants';import { useChatStores, useClipboardPaste } from '@react/features/ai-chat/hooks';import { createFileFromText } from '@react/features/ai-chat/utils';@@ -29,8 +30,16 @@ export const ChatInput = () => {const inputRef = useRef<HTMLTextAreaElement>(null);const fileInputRef = useRef<HTMLInputElement>(null);- const { isStreaming, isChatCreating, isProcessing, sendMessage, stopGenerating } = chat || {};- const { data: files, uploadingIds, addFiles, removeFile, clearFiles } = filesData || {};+ const { isChatCreating } = chat || {};+ const { isStreaming, sendMessage, stopStreaming } = chat || {};+ const {+ attachments: files,+ status: uploadStatus,+ process: addFiles,+ remove: removeFile,+ clear: clearFiles,+ uploading,+ } = filesData || {};const maxLength = MAX_CHAT_MESSAGE_LENGTH;const isMaxFilesUploaded = files.length >= 10;@@ -114,11 +123,12 @@ export const ChatInput = () => {);const handleSubmit = useCallback((): void => {- if (isStreaming) return stopGenerating();+ if (isStreaming) return stopStreaming();const trimmedMessage = message.trim();if (trimmedMessage.length > 0 || files.length > 0) {- sendMessage(trimmedMessage, files);+ // sendMessage(trimmedMessage, files);+ sendMessage(trimmedMessage);setMessage('');clearFiles();@@ -228,9 +238,13 @@ export const ChatInput = () => {{files.map((fileWithMetadata, index) => (<FileItemPreviewkey={`${fileWithMetadata.id}`}- file={fileWithMetadata}+ fileObj={fileWithMetadata.file}+ url={fileWithMetadata.url}+ blobUrl={fileWithMetadata.blobUrl}+ mimeType={fileWithMetadata.type}+ fileName={fileWithMetadata.name}onRemove={() => handleRemoveFile(index)}- isUploading={uploadingIds.has(fileWithMetadata.id)}+ isUploading={uploadStatus[fileWithMetadata.name]?.status === 'uploading'}/>))}</div>@@ -277,15 +291,15 @@ export const ChatInput = () => {<div onClick={(e) => e.stopPropagation()}><AttachmentButtononClick={handleAttachmentClick}- fileAttachmentDisabled={isMaxFilesUploaded || isDisabled || isProcessing || isStreaming}+ fileAttachmentDisabled={isMaxFilesUploaded || isDisabled || isStreaming}isMaxFilesUploaded={isMaxFilesUploaded}/></div><div onClick={(e) => e.stopPropagation()}><SendButton- isProcessing={isProcessing || isStreaming}- disabled={!canSubmit || uploadingIds.size > 0}+ isStreaming={isStreaming}+ disabled={!canSubmit || uploading}onClick={handleSubmit}/></div>diff --git a/packages/app/src/react/features/ai-chat/components/send-button.tsx b/packages/app/src/react/features/ai-chat/components/send-button.tsxindex 5a32524f..9f75f7a3 100644--- a/packages/app/src/react/features/ai-chat/components/send-button.tsx+++ b/packages/app/src/react/features/ai-chat/components/send-button.tsx@@ -5,12 +5,12 @@ import { Button } from '@react/shared/components/ui/newDesign/button';import { cn } from '@src/react/shared/utils/general';interface SendButtonProps {- isProcessing: boolean;+ isStreaming: boolean;disabled: boolean;onClick: () => void;}-export const SendButton: FC<SendButtonProps> = ({ isProcessing, disabled, onClick }) => (+export const SendButton: FC<SendButtonProps> = ({ isStreaming, disabled, onClick }) => (<ButtonaddIconvariant="primary"@@ -18,10 +18,10 @@ export const SendButton: FC<SendButtonProps> = ({ isProcessing, disabled, onClichandleClick={onClick}className={cn('h-[40px] w-[40px] rounded-lg px-0 py-0',- isProcessing ? 'chat-stop' : 'chat-send',+ isStreaming ? 'chat-stop' : 'chat-send',)}Icon={- isProcessing ? (+ isStreaming ? (<FaStop fontSize={14} />) : (<svgdiff --git a/packages/app/src/react/features/ai-chat/components/thinking-message.tsx b/packages/app/src/react/features/ai-chat/components/thinking-message.tsxindex f894cc29..9b4ef1f0 100644--- a/packages/app/src/react/features/ai-chat/components/thinking-message.tsx+++ b/packages/app/src/react/features/ai-chat/components/thinking-message.tsx@@ -1,9 +1,9 @@-import { IMetaMessages } from '@react/features/ai-chat/types/chat.types';import {createThinkingManager,formatStatusMessage,} from '@react/features/ai-chat/utils/stream.utils';import { FC, useEffect, useRef, useState } from 'react';+import { IMetaMessages } from '../types/chat';interface IProps {avatar?: string;diff --git a/packages/app/src/react/features/ai-chat/components/user-message.tsx b/packages/app/src/react/features/ai-chat/components/user-message.tsxindex 287c2915..d74b5e59 100644--- a/packages/app/src/react/features/ai-chat/components/user-message.tsx+++ b/packages/app/src/react/features/ai-chat/components/user-message.tsx@@ -1,13 +1,13 @@-import { FileItemPreview } from '@react/features/ai-chat/components';-import { IMessageFile } from '@react/features/ai-chat/types/chat.types';import { FC } from 'react';+import { IAttachment } from '../types/chat';+import { FileItemPreview } from './FileItemPreview';/*** User Message Component Properties*/interface IUserMessage {message: string;- files?: IMessageFile[];+ files?: IAttachment[];}/**@@ -23,13 +23,16 @@ export const UserMessage: FC<IUserMessage> = ({ message, files }) => {{/* File Attachments */}{hasFiles && (<div className="flex flex-nowrap gap-2 mb-2 overflow-x-auto">- {files.map((fileWithKey, index) => (+ {files.map((attachment, index) => (<FileItemPreview+ key={`${attachment.name}-${index}-${attachment.url || attachment.blobUrl || index}`}+ fileObj={attachment.file}+ url={attachment.url}+ blobUrl={attachment.blobUrl}+ mimeType={attachment.type}+ fileName={attachment.name}isReadOnly- key={fileWithKey.id || index}- file={fileWithKey}- fileKey={fileWithKey.metadata.key}- inChatBubble={true}+ inChatBubble/>))}</div>diff --git a/packages/app/src/react/features/ai-chat/constants/index.ts b/packages/app/src/react/features/ai-chat/constants/index.tsindex 57c2b393..2244e7c1 100644--- a/packages/app/src/react/features/ai-chat/constants/index.ts+++ b/packages/app/src/react/features/ai-chat/constants/index.ts@@ -1,8 +1,19 @@+import { TMessageType } from '@react/features/ai-chat/types/chat.types';+export const CHAT_ACCEPTED_FILE_TYPES = {mime: ['*/*'] as const,input: '*/*' as const,} as const;+/** Supported file types for upload - accepts all types */+export const SUPPORTED_FILE_TYPES = ['*/*'] as const;++/** Maximum allowed file size in bytes (5MB) */+export const ALLOWED_FILE_SIZE = 5 * 1024 * 1024;++/** Maximum number of files that can be uploaded at once */+export const MAX_UPLOADS = 5;+export const CHAT_ERROR_MESSAGE ='An error occurred. If the issue persists, please send message via our feedback channel. [discord.gg/smythos](https://discord.gg/smythos)';@@ -10,3 +21,14 @@ export const USER_STOPPED_MESSAGE = 'Generation interrupted by user';export const DEFAULT_AVATAR_URL ='https://gravatar.com/avatar/ccd5b19e810febbfd3d4321e27b15f77?s=400&d=mp&r=x';++// Message types+type TMessageKey = 'USER' | 'SYSTEM' | 'ERROR' | 'DEBUG' | 'META' | 'LOADING';+export const MESSAGE_TYPES: Record<TMessageKey, TMessageType> = {+ USER: 'user',+ SYSTEM: 'system',+ ERROR: 'error',+ DEBUG: 'debug',+ META: 'meta',+ LOADING: 'loading',+};diff --git a/packages/app/src/react/features/ai-chat/contexts/chat.tsx b/packages/app/src/react/features/ai-chat/contexts/chat.tsxindex e48b5993..24717b47 100644--- a/packages/app/src/react/features/ai-chat/contexts/chat.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/chat.tsx@@ -1,5 +1,6 @@/* eslint-disable no-unused-vars */-import { ChatInputRef, IChatMessage, IMessageFile } from '@react/features/ai-chat/types/chat.types';+import { IFileUpload, IMessage } from '@react/features/ai-chat/types/chat';+import { ChatInputRef } from '@react/features/ai-chat/types/chat.types';import { AgentDetails, AgentSettings } from '@react/shared/types/agent-data.types';import { createContext, Dispatch, MutableRefObject, SetStateAction } from 'react';@@ -10,29 +11,19 @@ export interface IChatContext {settings?: AgentSettings;isLoading: { agent: boolean; settings: boolean };};- files: {- isLoading: boolean;- errorMessage: string;- data: IMessageFile[];- uploadingIds: Set<string>;- addFiles: (newFiles: File[]) => Promise<void>;- removeFile: (index: number) => Promise<void>;- clearError: () => void;- clearFiles: () => void;- clearAll: () => void;- };+ /** File upload management using V2 hook */+ files: IFileUpload;chat: {// StateisChatCreating: boolean;- messages: IChatMessage[];+ messages: IMessage[];isStreaming: boolean;- isProcessing: boolean;// ActionscreateSession: () => Promise<void>;- sendMessage: (message: string, files?: File[] | IMessageFile[]) => Promise<void>;- retryMessage: () => Promise<void>;- stopGenerating: () => void;+ sendMessage: (message: string) => Promise<void>;+ retryMessage: () => void;+ stopStreaming: () => void;clearMessages: () => void;resetSession: () => Promise<void>;};@@ -54,25 +45,30 @@ export const ChatContext = createContext<IChatContext>({ref: { input: undefined, container: undefined },agent: { data: undefined, settings: undefined, isLoading: { agent: false, settings: false } },files: {- data: [],- isLoading: false,+ attachments: [],+ status: {},+ uploading: false,+ toast: '',+ showToast: false,errorMessage: '',- uploadingIds: new Set(),- addFiles: async () => {},- removeFile: async () => {},- clearError: () => {},- clearFiles: () => {},- clearAll: () => {},+ inputRef: { current: null },+ onSelect: async () => {},+ process: async () => {},+ remove: () => {},+ clear: () => {},+ cleanup: () => {},+ setShowToast: () => {},+ setToast: () => {},+ setErrorMessage: () => {},},chat: {isChatCreating: false,messages: [],isStreaming: false,- isProcessing: false,createSession: async () => {},sendMessage: async () => {},retryMessage: async () => {},- stopGenerating: () => {},+ stopStreaming: () => {},clearMessages: () => {},resetSession: async () => {},},diff --git a/packages/app/src/react/features/ai-chat/contexts/index.tsx b/packages/app/src/react/features/ai-chat/contexts/index.tsxindex fd07427c..124d1a44 100644--- a/packages/app/src/react/features/ai-chat/contexts/index.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/index.tsx@@ -1,11 +1,11 @@import {useAgentSettings,- useAttachments,- useChat,useCreateChatMutation,useScrollToBottom,useUpdateAgentSettingsMutation,} from '@react/features/ai-chat/hooks';+import { useChatState } from '@react/features/ai-chat/hooks/use-chat-state';+import { useFileUpload } from '@react/features/ai-chat/hooks/use-file-upload';import { ChatInputRef, IChildren } from '@react/features/ai-chat/types/chat.types';import { useAgent } from '@react/shared/hooks/agent';import { Observability } from '@shared/observability';@@ -23,8 +23,7 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {const navigate = useNavigate();- // Internal refs for tracking state- const isFirstMessageSentRef = useRef(false);+ // Internal ref for tracking initialization stateconst hasInitializedChatRef = useRef(false);// Model override state (temporary, not saved to agent config)@@ -51,7 +50,10 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {// FILE UPLOAD MANAGEMENT// ============================================================================- const files = useAttachments({ agentId, chatId: agentSettings?.lastConversationId });+ const fileUpload = useFileUpload({+ agentId: agentId || '',+ chatId: agentSettings?.lastConversationId || '',+ });// ============================================================================// SCROLL BEHAVIOR@@ -63,26 +65,23 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {// CHAT STATE MANAGEMENT// ============================================================================+ const chatStateV2 = useChatState({+ agentId: agentId || '',+ chatId: agentSettings?.lastConversationId || '',+ modelId: modelOverride || agentSettings?.chatGptModel,+ enableMetaMessages: true,+ inputRef,+ });++ // Destructure for easier accessconst {messages,+ setMessages,isStreaming,- isProcessing,-- sendMessage: sendChatMessage,- retryMessage,- clearMessages,- stopGenerating,- } = useChat({- agentId,- chatId: agentSettings?.lastConversationId || '',- modelId: modelOverride || agentSettings?.chatGptModel, // Use override if set, otherwise fall back to agent's default model- onChatComplete: () => {- if (!isFirstMessageSentRef.current) {- isFirstMessageSentRef.current = true;- }- },- onError: (err) => console.error('Chat error:', err), // eslint-disable-line no-console- });+ sendMessage: sendMessageV2,+ stopStreaming,+ retryLastMessage,+ } = chatStateV2;// ============================================================================// CHAT ACTIONS@@ -94,23 +93,28 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {*/const sendMessage = useCallback(async (message: string) => {- if (!message.trim() && files.data.length === 0) return;+ if (!message.trim() && fileUpload.attachments.length === 0) return;try {- // Send message with already-uploaded files- const filesForChat =- files.data.length > 0- ? (files.data as unknown as Parameters<typeof sendChatMessage>[1])- : undefined;- await sendChatMessage(message, filesForChat);+ // Convert V2 attachments to IAttachment format+ const attachments = fileUpload.attachments.map((f) => ({+ name: f.name,+ type: f.type,+ size: f.size,+ url: f.url,+ blobUrl: f.blobUrl,+ file: f.file,+ }));++ await sendMessageV2(message, attachments);// Clear files after successful send- files.clearFiles();+ fileUpload.clear();} catch (error) {console.error('Failed to send message:', error); // eslint-disable-line no-console}},- [files, sendChatMessage],+ [fileUpload, sendMessageV2],);/**@@ -141,10 +145,9 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {* Clears current chat session and creates a new one*/const resetSession = useCallback(async () => {- stopGenerating();- isFirstMessageSentRef.current = false;- clearMessages();- files.clearFiles();+ stopStreaming();+ setMessages([]);+ fileUpload.clear();await createSession();// Trigger callback@@ -153,7 +156,7 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {// Track observability eventsObservability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);- }, [createSession, clearMessages, files, stopGenerating, inputRef]);+ }, [createSession, setMessages, fileUpload, stopStreaming, inputRef]);// ============================================================================// LIFECYCLE EFFECTS@@ -187,9 +190,9 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {* Auto-focus input when agent is loaded and not disabled*/useEffect(() => {- const inputDisabled = isChatCreating || isAgentLoading || isProcessing;+ const inputDisabled = isChatCreating || isAgentLoading || isStreaming;if (!isAgentLoading && !inputDisabled) inputRef.current?.focus();- }, [isAgentLoading, isChatCreating, isProcessing]);+ }, [isAgentLoading, isChatCreating, isStreaming]);// Memoize the store to avoid unnecessary re-rendersconst values: IChatContext = useMemo(@@ -200,18 +203,17 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {settings: agentSettings,isLoading: { agent: isAgentLoading, settings: isAgentSettingsLoading },},- files,+ files: fileUpload,chat: {isChatCreating,messages,isStreaming,- isProcessing,- createSession,sendMessage,- retryMessage,- stopGenerating,- clearMessages,resetSession,+ createSession,+ stopStreaming,+ retryMessage: retryLastMessage,+ clearMessages: () => setMessages([]),},scroll,@@ -226,21 +228,17 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {agentSettings,isAgentLoading,isAgentSettingsLoading,- files,-+ fileUpload,isChatCreating,messages,isStreaming,- isProcessing,createSession,sendMessage,- retryMessage,- stopGenerating,- clearMessages,+ retryLastMessage,+ stopStreaming,+ setMessages,resetSession,-scroll,-modelOverride,setModelOverride,],diff --git a/packages/app/src/react/features/ai-chat/hooks/index.ts b/packages/app/src/react/features/ai-chat/hooks/index.tsindex 718b6bb5..1235c2f1 100644--- a/packages/app/src/react/features/ai-chat/hooks/index.ts+++ b/packages/app/src/react/features/ai-chat/hooks/index.ts@@ -1,9 +1,6 @@export * from './use-agent-settings';-export * from './use-attachments';-export * from './use-chat';-export * from './use-chat-stream';-export * from './use-clipboard-paste';export * from './use-chat-mutation';+export * from './use-clipboard-paste';export * from './use-drag-and-drop';export * from './use-scroll';export * from './use-store';diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-state.tsindex 029219a6..82d958b5 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts@@ -29,6 +29,17 @@ export const useChatState = (options: IConfigOptions): IChatState => {if (!lastMessage) return prev;+ if (lastMessage.type === MESSAGE_TYPES.META) {+ updated[lastIdx] = {+ ...lastMessage,+ type: MESSAGE_TYPES.SYSTEM,+ content: content,+ metaMessages: undefined,+ updatedAt: Date.now(),+ };+ return updated;+ }+if (lastMessage.type === MESSAGE_TYPES.LOADING) {updated[lastIdx] = {...lastMessage,diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat.tsindex bf8a90d3..6d3d125f 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-chat.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat.ts@@ -207,7 +207,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {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 === 'thinking') {+ if (lastMessage?.type === 'loading' || lastMessage?.type === 'meta') {return prev.map((msg, index) =>index === prev.length - 1? {@@ -281,7 +281,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {if (isThinkingRef.current) {setMessages((prev) => {const lastMessageIndex = prev.length - 1;- if (lastMessageIndex >= 0 && prev[lastMessageIndex].type === 'thinking') {+ if (lastMessageIndex >= 0 && prev[lastMessageIndex].type === 'meta') {// Replace thinking message with loading messageconst newMessages = prev.slice(0, -1);newMessages.push({@@ -482,12 +482,11 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {// Statemessages,isStreaming,- isProcessing,// ActionssendMessage,clearMessages,retryMessage: retryLastMessage,- stopGenerating,+ stopStreaming: stopGenerating,};};diff --git a/packages/app/src/react/features/ai-chat/types/chat.types.ts b/packages/app/src/react/features/ai-chat/types/chat.types.tsindex 2d396d19..2af19ec8 100644--- a/packages/app/src/react/features/ai-chat/types/chat.types.ts+++ b/packages/app/src/react/features/ai-chat/types/chat.types.ts@@ -160,12 +160,11 @@ export interface IUseChatReturn {// Statemessages: IChatMessage[];isStreaming: boolean;- isProcessing: boolean;// ActionssendMessage: (message: string, files?: File[] | IMessageFile[]) => Promise<void>;retryMessage: () => Promise<void>;- stopGenerating: () => void;+ stopStreaming: () => void;clearMessages: () => void;}diff --git a/packages/app/src/react/features/ai-chat/utils/file.ts b/packages/app/src/react/features/ai-chat/utils/file.tsindex b7e90671..86a38d7b 100644--- a/packages/app/src/react/features/ai-chat/utils/file.ts+++ b/packages/app/src/react/features/ai-chat/utils/file.ts@@ -63,3 +63,91 @@ export const createFileMetadata = (file: File): IMessageFile => ({id: generateUniqueFileId(file),metadata: { fileType: file.type, previewUrl: getLocalPreviewUrl(file), isUploading: true },});++/**+ * Interface for upload files props+ */+interface IUploadFilesProps {+ files: File[];+ agentId?: string;+ chatId?: string;+}++/**+ * Interface for upload response+ */+interface IUploadResponse {+ files?: Array<{+ url: string;+ name?: string;+ type?: string;+ size?: number;+ mimetype?: string;+ }>;+}++/**+ * Uploads files to the server+ *+ * @param props - Upload configuration+ * @returns Promise with upload response containing file URLs+ *+ * @example+ * ```typescript+ * const response = await uploadFiles({+ * files: [file1, file2],+ * agentId: 'agent-123',+ * chatId: 'chat-456',+ * });+ * console.log(response.files[0].url);+ * ```+ */+export const uploadFiles = async (props: IUploadFilesProps): Promise<IUploadResponse> => {+ const { files, agentId, chatId } = props;++ try {+ const formData = new FormData();+ files.forEach((file) => {+ formData.append('file', file);+ });++ const headers: Record<string, string> = {};++ // Add agent and chat IDs if provided+ if (agentId) {+ headers['X-AGENT-ID'] = agentId;+ }+ if (chatId) {+ headers['x-conversation-id'] = chatId;+ }++ const response = await fetch('/api/page/chat/upload', {+ method: 'POST',+ headers,+ body: formData,+ });++ if (!response.ok) {+ throw new Error(`Upload failed: ${response.statusText}`);+ }++ const data = await response.json();++ // Normalize response structure+ const runtimeFiles = data?.files || (data?.file ? [data.file] : []);++ return {+ files: runtimeFiles.map(+ (f: { url?: string; publicUrl?: string; mimetype?: string; type?: string; name?: string; size?: number }) => ({+ url: f.url || f.publicUrl || '',+ name: f.name,+ type: f.mimetype || f.type,+ size: f.size,+ }),+ ),+ };+ } catch (error) {+ console.error('Error uploading files:', error); // eslint-disable-line no-console+ throw error;+ }+};\ No newline at end of file