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 AI Chat Components for Improved File Handling and Error Management
Salman-Ahamedaf0d93f79024
diff --git a/packages/app/src/react/features/ai-chat/components/chat/chats.tsx b/packages/app/src/react/features/ai-chat/components/chat/chats.tsxindex b1201af9..292211a5 100644--- a/packages/app/src/react/features/ai-chat/components/chat/chats.tsx+++ b/packages/app/src/react/features/ai-chat/components/chat/chats.tsx@@ -30,7 +30,7 @@ export const Chats: FC = () => {const agent = agentData?.data;const containerRef = allRefs?.container;- const handleFileDrop = files.process;+ const handleFileDrop = files.addFiles;const ref = useRef<HTMLDivElement>(null);const dropzoneRef = useDragAndDrop({ onDrop: handleFileDrop });diff --git a/packages/app/src/react/features/ai-chat/components/footer/footer.tsx b/packages/app/src/react/features/ai-chat/components/footer/footer.tsxindex e0fa8aad..6599a4da 100644--- a/packages/app/src/react/features/ai-chat/components/footer/footer.tsx+++ b/packages/app/src/react/features/ai-chat/components/footer/footer.tsx@@ -1,23 +1,20 @@import { ChatInput, ErrorToast, ScrollToBottomButton } from '@react/features/ai-chat/components';import { useChatStores } from '@react/features/ai-chat/hooks';-import { FC, useCallback } from 'react';+import { FC } from 'react';const CHAT_WARNING_INFO ="SmythOS can make mistakes, always check your work. We don't store chat history, save important work."; // eslint-disable-line quotesexport const Footer: FC = () => {const { files, scroll } = useChatStores();- const { errorMessage, setErrorMessage } = files;+ const { errorMessage, clearError } = 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={onClose} />}+ {errorMessage && <ErrorToast message={errorMessage} onClose={clearError} />}<div className="relative">- {showScrollButton && <ScrollToBottomButton onClick={onScrollToBottom} />}+ {showScrollButton && <ScrollToBottomButton onClick={() => scrollToBottom()} />}<ChatInput /></div>diff --git a/packages/app/src/react/features/ai-chat/components/footer/input.tsx b/packages/app/src/react/features/ai-chat/components/footer/input.tsxindex dccf357a..4c1e3239 100644--- a/packages/app/src/react/features/ai-chat/components/footer/input.tsx+++ b/packages/app/src/react/features/ai-chat/components/footer/input.tsx@@ -24,7 +24,7 @@ export const ChatInput = () => {const { isChatCreating } = chat || {};const { isStreaming, sendMessage, stopStreaming } = chat || {};- const { attachments, status, process, remove, clear, uploading } = filesData || {};+ const { attachments, status, addFiles, remove, clear, uploading } = filesData || {};const maxLength = MAX_CHAT_MESSAGE_LENGTH;const isMaxFilesUploaded = attachments.length >= 10;@@ -94,10 +94,10 @@ export const ChatInput = () => {);useClipboardPaste({- onFilePaste: process,+ onFilePaste: addFiles,targetRef: inputRef,largeTextThreshold: LARGE_TEXT_THRESHOLD,- onLargeTextPaste: (text) => process([createFileFromText(text).file]),+ onLargeTextPaste: (text) => addFiles([createFileFromText(text).file]),});const isMaxLengthReached = message.length === maxLength;@@ -158,7 +158,7 @@ export const ChatInput = () => {<div onClick={(e) => e.stopPropagation()}><AttachmentButton- onFilesAdd={process}+ onFilesAdd={addFiles}fileInputRef={fileInputRef}isDisabled={isDisabled || isStreaming}isMaxFilesUploaded={isMaxFilesUploaded}diff --git a/packages/app/src/react/features/ai-chat/components/header/AgentAvatar.tsx b/packages/app/src/react/features/ai-chat/components/header/AgentAvatar.tsxnew file mode 100644index 00000000..6499d872--- /dev/null+++ b/packages/app/src/react/features/ai-chat/components/header/AgentAvatar.tsx@@ -0,0 +1,22 @@+import { FC } from 'react';+import { Skeleton } from '..';+import { DEFAULT_AVATAR_URL } from '../../constants';++interface AgentAvatarProps {+ avatar: string | undefined;+ isLoading: boolean;+}++export const AgentAvatar: FC<AgentAvatarProps> = ({ avatar, isLoading }) => (+ <figure>+ {isLoading ? (+ <Skeleton className="size-8 rounded-full" />+ ) : (+ <img+ src={avatar ?? DEFAULT_AVATAR_URL}+ alt="avatar"+ className="size-8 rounded-full transition-opacity duration-300 ease-in-out"+ />+ )}+ </figure>+);diff --git a/packages/app/src/react/features/ai-chat/components/header/AgentName.tsx b/packages/app/src/react/features/ai-chat/components/header/AgentName.tsxnew file mode 100644index 00000000..818b090b--- /dev/null+++ b/packages/app/src/react/features/ai-chat/components/header/AgentName.tsx@@ -0,0 +1,23 @@+import { cn } from '@src/react/shared/utils/general';+import { FC } from 'react';+import { Skeleton } from '..';++interface IProps {+ name: string | undefined;+ isAgentLoading: boolean;+ isSettingsLoading: boolean;+}++export const AgentName: FC<IProps> = ({ name, isAgentLoading, isSettingsLoading }) => {+ if (isAgentLoading) {+ return (+ <Skeleton className={cn('w-25 h-[18px] rounded', isSettingsLoading && 'rounded-b-none')} />+ );+ }++ return (+ <span className="text-lg font-medium text-[#111827] transition-opacity duration-300 ease-in-out leading-none">+ {name ?? 'Unknown Agent'}+ </span>+ );+};diff --git a/packages/app/src/react/features/ai-chat/components/header/index.ts b/packages/app/src/react/features/ai-chat/components/header/index.tsindex eb0c1af0..019453a8 100644--- a/packages/app/src/react/features/ai-chat/components/header/index.ts+++ b/packages/app/src/react/features/ai-chat/components/header/index.ts@@ -1,3 +1,5 @@+export * from './AgentAvatar';+export * from './AgentName';export * from './header-actions';export * from './main';export * from './model-dropdown';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.tsxindex f57553c9..82db290c 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@@ -1,13 +1,9 @@import { useQuery } from '@tanstack/react-query';-import { FC } from 'react';import { Skeleton } from '@react/features/ai-chat/components';-import { DEFAULT_AVATAR_URL } from '@react/features/ai-chat/constants';import { useChatStores } from '@react/features/ai-chat/hooks';-import { cn } from '@react/shared/utils/general';-import { HeaderActions } from './header-actions';-import { ModelDropdown } from './model-dropdown';+import { AgentAvatar, AgentName, HeaderActions, ModelDropdown } from '.';interface ModelAgent {id: string;@@ -22,7 +18,7 @@ const fetchModelAgents = async (): Promise<ModelAgent[]> => {return data.agents;};-export const Header: FC = () => {+export const Header = () => {const { agent: agentData, chat, modelOverride, setModelOverride } = useChatStores() || {};const { data: agent, settings, isLoading } = agentData || {};@@ -70,42 +66,3 @@ export const Header: FC = () => {</div>);};--interface AgentAvatarProps {- avatar: string | undefined;- isLoading: boolean;-}--const AgentAvatar: FC<AgentAvatarProps> = ({ avatar, isLoading }) => (- <figure>- {isLoading ? (- <Skeleton className="size-8 rounded-full" />- ) : (- <img- src={avatar ?? DEFAULT_AVATAR_URL}- alt="avatar"- className="size-8 rounded-full transition-opacity duration-300 ease-in-out"- />- )}- </figure>-);--interface AgentNameProps {- name: string | undefined;- isAgentLoading: boolean;- isSettingsLoading: boolean;-}--const AgentName: FC<AgentNameProps> = ({ name, isAgentLoading, isSettingsLoading }) => {- if (isAgentLoading) {- return (- <Skeleton className={cn('w-25 h-[18px] rounded', isSettingsLoading && 'rounded-b-none')} />- );- }-- return (- <span className="text-lg font-medium text-[#111827] transition-opacity duration-300 ease-in-out leading-none">- {name ?? 'Unknown Agent'}- </span>- );-};diff --git a/packages/app/src/react/features/ai-chat/contexts/chat.tsx b/packages/app/src/react/features/ai-chat/contexts/chat.tsxindex 8c887e85..8cc6a5fd 100644--- a/packages/app/src/react/features/ai-chat/contexts/chat.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/chat.tsx@@ -1,7 +1,7 @@/* eslint-disable no-unused-vars */import { IFileUpload, IMessage } from '@react/features/ai-chat/types/chat';import { AgentDetails, AgentSettings } from '@react/shared/types/agent-data.types';-import { createContext, Dispatch, RefObject, SetStateAction } from 'react';+import { createContext, RefObject } from 'react';export interface IChatContext {/** Refs for input textarea and chat container (chatbot pattern - direct element refs) */@@ -17,27 +17,19 @@ export interface IChatContext {/** File upload management using V2 hook */files: IFileUpload;chat: {- // StateisChatCreating: boolean;messages: IMessage[];isStreaming: boolean;-- // Actions- createSession: () => Promise<void>;sendMessage: (message: string) => Promise<void>;retryMessage: () => void;stopStreaming: () => void;- clearMessages: () => void;resetSession: () => Promise<void>;};scroll: {showScrollButton: boolean;- shouldAutoScroll: boolean;handleScroll: () => void;scrollToBottom: (smooth?: boolean) => void;smartScrollToBottom: (smooth?: boolean) => void;- setShowScrollButton: Dispatch<SetStateAction<boolean>>;- setShouldAutoScroll: Dispatch<SetStateAction<boolean>>;};// Model override (temporary, not saved to agent config)modelOverride: string | null;@@ -51,38 +43,26 @@ export const ChatContext = createContext<IChatContext>({attachments: [],status: {},uploading: false,- toast: '',- showToast: false,errorMessage: '',- inputRef: { current: null },- onSelect: async () => {},- process: async () => {},+ addFiles: async () => {},remove: () => {},clear: () => {},- cleanup: () => {},- setShowToast: () => {},- setToast: () => {},- setErrorMessage: () => {},+ clearError: () => {},},chat: {isChatCreating: false,messages: [],isStreaming: false,- createSession: async () => {},sendMessage: async () => {},retryMessage: async () => {},stopStreaming: () => {},- clearMessages: () => {},resetSession: async () => {},},scroll: {showScrollButton: false,- shouldAutoScroll: true,handleScroll: () => {},scrollToBottom: () => {},smartScrollToBottom: () => {},- setShowScrollButton: () => {},- setShouldAutoScroll: () => {},},modelOverride: null,setModelOverride: () => {},diff --git a/packages/app/src/react/features/ai-chat/contexts/index.tsx b/packages/app/src/react/features/ai-chat/contexts/index.tsxindex bd793ecf..2238d763 100644--- a/packages/app/src/react/features/ai-chat/contexts/index.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/index.tsx@@ -156,10 +156,8 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {isStreaming,sendMessage,resetSession,- createSession,stopStreaming,retryMessage: retryLastMessage,- clearMessages: () => setMessages([]),},scroll,@@ -178,11 +176,9 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {isChatCreating,messages,isStreaming,- createSession,sendMessage,retryLastMessage,stopStreaming,- setMessages,resetSession,scroll,modelOverride,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.tsindex a854f23a..8edf3f49 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@@ -23,11 +23,8 @@ export const useFileUpload = (options: IProps): IFileUpload => {const [status, setStatus] = useState<Record<string, IUploadStatus>>({});const [uploading, setUploading] = useState(false);const [errorMessage, setErrorMessage] = useState('');- const [toast, setToast] = useState('');- const [showToast, setShowToast] = useState(false);const blobsRef = useRef<Set<string>>(new Set());- const inputRef = useRef<HTMLInputElement>(null);useEffect(() => {let timer: ReturnType<typeof setTimeout>;@@ -57,13 +54,11 @@ export const useFileUpload = (options: IProps): IFileUpload => {delete next[fileName];return next;});-- if (inputRef.current) inputRef.current.value = '';},[attachments],);- const processFiles = useCallback(+ const addFiles = useCallback(async (files: File[]) => {if (files.length === 0) return;@@ -97,8 +92,7 @@ export const useFileUpload = (options: IProps): IFileUpload => {blobUrl = URL.createObjectURL(file);blobsRef.current.add(blobUrl);} catch (err) {- // eslint-disable-next-line no-console- console.error('[FileUpload] Error creating blob URL:', err);+ console.error('[FileUpload] Error creating blob URL:', err); // eslint-disable-line no-console}}return { id, file, blobUrl, name: file.name, type: file.type, size: file.size };@@ -154,14 +148,6 @@ export const useFileUpload = (options: IProps): IFileUpload => {[attachments.length, agentId, chatId, onError],);- const onSelect = useCallback(- async (e: React.ChangeEvent<HTMLInputElement>) => {- const files = Array.from(e.target.files || []).slice(0, MAX_UPLOADS);- await processFiles(files);- },- [processFiles],- );-const remove = useCallback((index: number) => {const target = attachments[index];@@ -173,8 +159,6 @@ export const useFileUpload = (options: IProps): IFileUpload => {delete next[target.name];return next;});-- if (inputRef.current) inputRef.current.value = '';},[attachments],);@@ -196,44 +180,22 @@ export const useFileUpload = (options: IProps): IFileUpload => {setAttachments([]);setStatus({});- if (inputRef.current) inputRef.current.value = '';},[attachments],);- const cleanup = useCallback(() => {- const active = new Set<string>();-- attachments.forEach((a) => {- if (a.blobUrl) active.add(a.blobUrl);- });-- const stale: string[] = [];- blobsRef.current.forEach((url) => {- if (!active.has(url)) {- URL.revokeObjectURL(url);- stale.push(url);- }- });-- stale.forEach((url) => blobsRef.current.delete(url));- }, [attachments]);+ const clearError = useCallback(() => {+ setErrorMessage('');+ }, [setErrorMessage]);return {attachments,status,uploading,- toast,- showToast,errorMessage,- inputRef,- onSelect,- process: processFiles,+ addFiles,remove,clear,- cleanup,- setShowToast,- setToast,- setErrorMessage,+ clearError,};};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.tsindex e8f3aa7d..1d8daa25 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@@ -4,7 +4,6 @@ import { scrollManager } from '@src/react/features/ai-chat/utils/scroll';export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {const [showScrollButton, setShowScrollButton] = useState(false);- const [shouldAutoScroll, setShouldAutoScroll] = useState(true);useEffect(() => {if (ref.current) scrollManager.init(ref.current);@@ -16,15 +15,10 @@ export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {if (ref.current) {const { scrollTop, scrollHeight, clientHeight } = ref.current;-const distanceFromBottom = Math.ceil(scrollHeight - scrollTop - clientHeight);const threshold = 200;-const isScrolledUp = distanceFromBottom > threshold;setShowScrollButton(isScrolledUp);-- const isNearBottom = distanceFromBottom <= threshold;- setShouldAutoScroll(isNearBottom);}}, [ref]);@@ -35,7 +29,6 @@ export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {top: ref.current.scrollHeight,behavior: smooth ? 'smooth' : 'auto',});- setShouldAutoScroll(true);}},[ref],@@ -57,9 +50,6 @@ export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {showScrollButton,handleScroll,scrollToBottom,- setShowScrollButton,- shouldAutoScroll,smartScrollToBottom,- setShouldAutoScroll,};};diff --git a/packages/app/src/react/features/ai-chat/types/chat.ts b/packages/app/src/react/features/ai-chat/types/chat.tsindex 01fafa7e..6204db30 100644--- a/packages/app/src/react/features/ai-chat/types/chat.ts+++ b/packages/app/src/react/features/ai-chat/types/chat.ts@@ -1,5 +1,5 @@/* eslint-disable no-unused-vars */-import type { ChangeEvent, Dispatch, RefObject, SetStateAction } from 'react';+import type { Dispatch, RefObject, SetStateAction } from 'react';// ============================================================================// MESSAGE TYPES@@ -178,16 +178,9 @@ export interface IFileUpload {attachments: IFileAttachment[];status: Record<string, IUploadStatus>;uploading: boolean;- toast: string;- showToast: boolean;errorMessage: string;- inputRef: RefObject<HTMLInputElement | null>;- onSelect: (e: ChangeEvent<HTMLInputElement>) => Promise<void>;- process: (files: File[]) => Promise<void>;+ addFiles: (files: File[]) => Promise<void>;remove: (index: number) => void;- clear: () => void;- cleanup: () => void;- setShowToast: (show: boolean) => void;- setToast: (message: string) => void;- setErrorMessage: (message: string) => void;+ clear: (preserveBlobUrls?: boolean) => void;+ clearError: () => void;}