SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
Refactor Chat Context and Provider Implementation
Salman-Ahamedeaf7c5f93437
diff --git a/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx b/packages/app/src/react/features/ai-chat/contexts/chat-context.tsxindex b1c0fb09..ff7badd1 100644--- a/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx@@ -1,9 +1,13 @@-import { createContext } from 'react';+import { ChatInputRef } from '@react/features/ai-chat/components/input';+import { AgentDetails, AgentSettings } from '@react/shared/types/agent-data.types';+import { createContext, MutableRefObject } from 'react';export interface IChatContext {- agentId: string;+ ref: { input?: MutableRefObject<ChatInputRef>; container?: MutableRefObject<HTMLDivElement> };+ agent: { data?: AgentDetails; settings?: AgentSettings; loading: boolean };}export const ChatContext = createContext<IChatContext>({- agentId: '',+ ref: { input: undefined, container: undefined },+ agent: { data: undefined, settings: undefined, loading: false },});diff --git a/packages/app/src/react/features/ai-chat/contexts/index.new.tsx b/packages/app/src/react/features/ai-chat/contexts/index.new.tsxindex 12dcbf2b..f3504cf9 100644--- a/packages/app/src/react/features/ai-chat/contexts/index.new.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/index.new.tsx@@ -1,15 +1,49 @@+import { ChatInputRef } from '@react/features/ai-chat/components/input';import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat-context';-import { FC, ReactNode, useMemo, useState } from 'react';+import { useAgent } from '@src/react/shared/hooks/agent';+import { FC, ReactNode, useMemo, useRef } from 'react';+import { useNavigate, useParams } from 'react-router-dom';+import { useAgentSettings } from '../hooks/agent-settings';interface IProps {children: ReactNode;}export const ChatContextProvider: FC<IProps> = ({ children }) => {- const [agentId] = useState('');+ const params = useParams<{ agentId: string }>();+ const agentId = params?.agentId;++ const inputRef = useRef<ChatInputRef>(null);+ const containerRef = useRef<HTMLDivElement>(null);++ const navigate = useNavigate();++ // ============================================================================+ // API HOOKS+ // ============================================================================++ const { data: agent, isLoading: isAgentLoading } = useAgent(agentId, {+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ retry: false,+ onError: () => navigate('/error/403'),+ });++ const { data: settingsData, isLoading: isAgentSettingsLoading } = useAgentSettings(agentId);+ const agentSettings = settingsData?.settings;// Memoize the store to avoid unnecessary re-renders- const values: IChatContext = useMemo(() => ({ agentId }), [agentId]);+ const values: IChatContext = useMemo(+ () => ({+ ref: { input: inputRef, container: containerRef },+ agent: {+ data: agent,+ settings: agentSettings,+ loading: isAgentLoading || isAgentSettingsLoading,+ },+ }),+ [inputRef, containerRef, agent, agentSettings, isAgentLoading, isAgentSettingsLoading],+ );return <ChatContext.Provider value={values}>{children}</ChatContext.Provider>;};diff --git a/packages/app/src/react/features/ai-chat/hooks/use-agent-chat-context.ts b/packages/app/src/react/features/ai-chat/hooks/use-agent-chat-context.tsindex 5dd789fc..c9a114bc 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-agent-chat-context.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-agent-chat-context.ts@@ -132,22 +132,19 @@ export const useAgentChatContext = (clearError,isUploadInProgress,clearFiles,- } = useFileUpload({- agentId,- chatId: agentSettings?.lastConversationId,- });+ } = useFileUpload({ agentId, chatId: agentSettings?.lastConversationId });// ============================================================================// CHAT STATE MANAGEMENT// ============================================================================const {- messages: messagesHistory,isGenerating,- isProcessing: isInputProcessing,- sendMessage: sendChatMessage,- retryLastMessage,stopGenerating,+ retryLastMessage,+ messages: messagesHistory,+ sendMessage: sendChatMessage,+ isProcessing: isInputProcessing,clearMessages: clearChatMessages,} = useChat({agentId,@@ -169,7 +166,7 @@ export const useAgentChatContext = (const inputDisabled = isChatCreating || isAgentLoading || isInputProcessing;const queryInputPlaceholder = agent ? `Message ${agent.name}...` : 'Message ...';- const isMaxFilesUploaded = files.length >= 10; // FILE_LIMITS.MAX_ATTACHED_FILES+ const isMaxFilesUploaded = files.length >= 10;// No conversion needed - using same types now! ✅const sharedMessagesHistory: IChatMessage[] = messagesHistory;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.tsnew file mode 100644index 00000000..6276809e--- /dev/null+++ b/packages/app/src/react/features/ai-chat/hooks/use-attachments.ts@@ -0,0 +1,143 @@+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 (files.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 uploadingFiles 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,+ 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],+ );++ return {+ files,+ isLoading,+ errorMessage,++ addFiles,+ removeFile,+ };+};diff --git a/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts b/packages/app/src/react/features/ai-chat/hooks/use-fileupload.tsindex d81620e7..f159036a 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts@@ -39,6 +39,7 @@ export const useFileUpload = (params?: {const agentId = params?.agentId || '';const chatId = params?.chatId;const [files, setFiles] = useState<IMessageFile[]>([]);+const [uploadingFiles, setUploadingFiles] = useState<Set<string>>(new Set());const [uploadError, setUploadError] = useState<FileUploadError>({ show: false, message: '' });diff --git a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsxindex 4ca78476..e798dbeb 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@@ -9,6 +9,7 @@ import {Footer,} from '@react/features/ai-chat/components';import { ChatProvider } from '@react/features/ai-chat/contexts';+import { ChatContextProvider } from '@react/features/ai-chat/contexts/index.new';import { useAgentChatContext, useScrollToBottom } from '@react/features/ai-chat/hooks';/**@@ -65,31 +66,33 @@ const AgentChatPage = () => {// ============================================================================return (- <ChatProvider value={chatContextValue}>- <Container>- <ChatHeader agent={agent} isLoading={isLoading} agentSettings={agentSettings?.settings} />+ <ChatContextProvider>+ <ChatProvider value={chatContextValue}>+ <Container>+ <ChatHeader agent={agent} isLoading={isLoading} agentSettings={agentSettings?.settings} />- <Chats- {...scroll}- agent={agent}- messages={sharedMessagesHistory}- containerRef={chatContainerRef}- handleFileDrop={handleFileDrop}- smartScrollToBottom={smartScrollToBottom}- />+ <Chats+ {...scroll}+ agent={agent}+ messages={sharedMessagesHistory}+ containerRef={chatContainerRef}+ handleFileDrop={handleFileDrop}+ smartScrollToBottom={smartScrollToBottom}+ />- <Footer- chatInputRef={chatInputRef}- clearError={chatContextValue.clearError}- uploadError={chatContextValue.uploadError}- scrollToBottom={scrollToBottom}- showScrollButton={showScrollButton}- submitDisabled={- isLoading.chatCreating || isLoading.agent || chatContextValue.uploadingFiles.size > 0- }- />- </Container>- </ChatProvider>+ <Footer+ chatInputRef={chatInputRef}+ clearError={chatContextValue.clearError}+ uploadError={chatContextValue.uploadError}+ scrollToBottom={scrollToBottom}+ showScrollButton={showScrollButton}+ submitDisabled={+ isLoading.chatCreating || isLoading.agent || chatContextValue.uploadingFiles.size > 0+ }+ />+ </Container>+ </ChatProvider>+ </ChatContextProvider>);};diff --git a/packages/app/src/react/features/ai-chat/utils/file.ts b/packages/app/src/react/features/ai-chat/utils/file.tsindex c3449496..b7e90671 100644--- a/packages/app/src/react/features/ai-chat/utils/file.ts+++ b/packages/app/src/react/features/ai-chat/utils/file.ts@@ -15,10 +15,7 @@ export const FILE_LIMITS = {* @returns {string | null} Preview URL or null if preview not possible*/export const getLocalPreviewUrl = (file: File): string | null => {- if (file.type.startsWith('image/')) {- return URL.createObjectURL(file);- }- return null;+ return file.type.startsWith('image/') ? URL.createObjectURL(file) : null;};/**@@ -52,6 +49,10 @@ export const deleteFile = async (key: string): Promise<boolean> => {}};+// Helper function to generate a unique ID for each file+export const generateUniqueFileId = (file: File): string => {+ return `${file.name}-${file.size}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;+};/*** Creates file metadata object from a file* @param file The file to create metadata for@@ -59,6 +60,6 @@ export const deleteFile = async (key: string): Promise<boolean> => {*/export const createFileMetadata = (file: File): IMessageFile => ({file,- id: `${file.name}-${file.size}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,+ id: generateUniqueFileId(file),metadata: { fileType: file.type, previewUrl: getLocalPreviewUrl(file), isUploading: true },});