SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
Refactor Chat Components and Context for Improved Structure and Type Safety
Salman-Ahamed542e2c2a1f4d
diff --git a/packages/app/src/react/features/ai-chat/components/container.tsx b/packages/app/src/react/features/ai-chat/components/container.tsxindex a94dee11..50428b6f 100644--- a/packages/app/src/react/features/ai-chat/components/container.tsx+++ b/packages/app/src/react/features/ai-chat/components/container.tsx@@ -1,8 +1,7 @@-import { FC, ReactNode, useCallback, useEffect, useRef } from 'react';+import { IChildren } from '@react/features/ai-chat/types/chat.types';+import { FC, useCallback, useEffect, useRef } from 'react';-type Props = { children: ReactNode };--export const Container: FC<Props> = ({ children }) => {+export const Container: FC<IChildren> = ({ children }) => {const parentElementRef = useRef<HTMLElement | null>(null);const originalStateRef = useRef<{ className: string; maxWidth: string } | null>(null);diff --git a/packages/app/src/react/features/ai-chat/components/file-item-preview.tsx b/packages/app/src/react/features/ai-chat/components/file-item-preview.tsxindex 44d61560..509daec0 100644--- a/packages/app/src/react/features/ai-chat/components/file-item-preview.tsx+++ b/packages/app/src/react/features/ai-chat/components/file-item-preview.tsx@@ -1,3 +1,4 @@+import { CloseIcon } from '@react/features/ai-chat/components/icons';import { IMessageFile } from '@react/features/ai-chat/types/chat.types';import classNames from 'classnames';import { FC, useEffect, useMemo, useState } from 'react';@@ -10,7 +11,6 @@ import {FaRegFileVideo,FaRegFileWord,} from 'react-icons/fa6';-import { CloseIcon } from './icons';interface FileItemPreviewProps {file: IMessageFile;diff --git a/packages/app/src/react/features/ai-chat/components/header.tsx b/packages/app/src/react/features/ai-chat/components/header.tsxindex 7331b464..3ba69d3c 100644--- a/packages/app/src/react/features/ai-chat/components/header.tsx+++ b/packages/app/src/react/features/ai-chat/components/header.tsx@@ -8,12 +8,12 @@ import { Link } from 'react-router-dom';import { Skeleton } from '@react/features/ai-chat/components';import { CloseIcon } from '@react/features/ai-chat/components/icons';import { DEFAULT_AVATAR_URL } from '@react/features/ai-chat/constants';+import { useChatStores } from '@react/features/ai-chat/hooks';import { cn } from '@src/react/shared/utils/general';import { Observability } from '@src/shared/observability';import { EVENTS } from '@src/shared/posthog/constants/events';import { LLMRegistry } from '@src/shared/services/LLMRegistry.service';import { llmModelsStore } from '@src/shared/state_stores/llm-models';-import { useChatStores } from '../hooks';// #region Temporary Badgesconst TEMP_BADGES: Record<string, boolean> = {@@ -68,6 +68,7 @@ export const ChatHeader: FC = () => {const { data: modelAgents } = useQuery<ModelAgent[]>({queryKey: ['modelAgents'],queryFn: fetchModelAgents,+ refetchOnWindowFocus: false,});// Check if current agent.id exists in modelAgents listdiff --git a/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx b/packages/app/src/react/features/ai-chat/contexts/chat.tsxsimilarity index 100%rename from packages/app/src/react/features/ai-chat/contexts/chat-context.tsxrename to packages/app/src/react/features/ai-chat/contexts/chat.tsxdiff --git a/packages/app/src/react/features/ai-chat/contexts/index.new.tsx b/packages/app/src/react/features/ai-chat/contexts/index.new.tsxdeleted file mode 100644index aca8bec0..00000000--- a/packages/app/src/react/features/ai-chat/contexts/index.new.tsx+++ /dev/null@@ -1,254 +0,0 @@-import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat-context';-import {- useAgentSettings,- useAttachments,- useChat,- useCreateChatMutation,- useScrollToBottom,- useUpdateAgentSettingsMutation,-} from '@react/features/ai-chat/hooks';-import { ChatInputRef } from '@react/features/ai-chat/types/chat.types';-import { useAgent } from '@react/shared/hooks/agent';-import { Observability } from '@shared/observability';-import { EVENTS } from '@shared/posthog/constants/events';-import { FC, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { useNavigate, useParams } from 'react-router-dom';--interface IProps {- children: ReactNode;-}--export const ChatContextProvider: FC<IProps> = ({ children }) => {- const params = useParams<{ agentId: string }>();- const agentId = params?.agentId;-- const inputRef = useRef<ChatInputRef>(null);- const containerRef = useRef<HTMLDivElement>(null);-- const navigate = useNavigate();-- // Internal refs for tracking state- const isFirstMessageSentRef = useRef(false);- 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,- retry: false,- onError: () => navigate('/error/403'),- });-- const { data: settingsData, isLoading: isAgentSettingsLoading } = useAgentSettings(agentId);- const { mutateAsync: createChat, isPending: isChatCreating } = useCreateChatMutation();- const { mutateAsync: updateAgentSettings } = useUpdateAgentSettingsMutation();-- const agentSettings = settingsData?.settings;-- // ============================================================================- // FILE UPLOAD MANAGEMENT- // ============================================================================-- const files = useAttachments({ agentId, chatId: agentSettings?.lastConversationId });-- // ============================================================================- // SCROLL BEHAVIOR- // ============================================================================-- const scroll = useScrollToBottom(containerRef);-- // ============================================================================- // CHAT STATE MANAGEMENT- // ============================================================================-- const {- messages,- 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- });-- // ============================================================================- // CHAT ACTIONS- // ============================================================================-- /**- * Sends a message with optional file attachments- * Integrates with the file upload system- */- const sendMessage = useCallback(- async (message: string) => {- if (!message.trim() && files.data.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);-- // Clear files after successful send- files.clearFiles();- } catch (error) {- console.error('Failed to send message:', error); // eslint-disable-line no-console- }- },- [files, sendChatMessage],- );-- /**- * Creates a new chat session/conversation- */- const createSession = useCallback(async () => {- try {- const conversation = await createChat({- conversation: {- summary: '',- chunkSize: 100,- lastChunkID: '0',- label: 'New Chat',- aiAgentId: agentId,- },- });-- await updateAgentSettings({- agentId,- settings: { key: 'lastConversationId', value: conversation?.id },- });- } catch (error) {- console.error('Error creating chat session', error); // eslint-disable-line no-console- }- }, [agentId, createChat, updateAgentSettings]);-- /**- * Clears current chat session and creates a new one- */- const resetSession = useCallback(async () => {- stopGenerating();- isFirstMessageSentRef.current = false;- clearMessages();- files.clearFiles();- 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, clearMessages, files, stopGenerating, 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-- /**- * 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 || isProcessing;- if (!isAgentLoading && !inputDisabled) inputRef.current?.focus();- }, [isAgentLoading, isChatCreating, isProcessing]);-- // Memoize the store to avoid unnecessary re-renders- const values: IChatContext = useMemo(- () => ({- ref: { input: inputRef, container: containerRef },- agent: {- data: agent,- settings: agentSettings,- isLoading: { agent: isAgentLoading, settings: isAgentSettingsLoading },- },- files,- chat: {- isChatCreating,- messages,- isStreaming,- isProcessing,- createSession,- sendMessage,- retryMessage,- stopGenerating,- clearMessages,- resetSession,- },-- scroll,-- modelOverride,- setModelOverride,- }),- [- inputRef,- containerRef,- agent,- agentSettings,- isAgentLoading,- isAgentSettingsLoading,- files,-- isChatCreating,- messages,- isStreaming,- isProcessing,- createSession,- sendMessage,- retryMessage,- stopGenerating,- clearMessages,- resetSession,-- scroll,-- modelOverride,- setModelOverride,- ],- );-- return <ChatContext.Provider value={values}>{children}</ChatContext.Provider>;-};diff --git a/packages/app/src/react/features/ai-chat/contexts/index.tsx b/packages/app/src/react/features/ai-chat/contexts/index.tsxindex 8ad7fbec..fd07427c 100644--- a/packages/app/src/react/features/ai-chat/contexts/index.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/index.tsx@@ -1,55 +1,250 @@-/* eslint-disable no-unused-vars */-import { IChatMessage, IMessageFile } from '@react/features/ai-chat/types/chat.types';-import { ChangeEvent, createContext, FC, PropsWithChildren, useContext } from 'react';--interface ChatContextType {- files: IMessageFile[];- uploadingFiles: Set<string>;- isUploadInProgress: boolean;- isMaxFilesUploaded: boolean;- handleFileChange: (e: ChangeEvent<HTMLInputElement>) => void;- handleFileDrop: (files: File[]) => Promise<void>;- removeFile: (fileKey: number) => void;- clearFiles: () => void;- uploadError: { show: boolean; message: string };- clearError: () => void;-- isRetrying: boolean;- isGenerating: boolean;- inputDisabled: boolean;- inputPlaceholder: string;- isInputProcessing: boolean;- messagesHistory: IChatMessage[];-- sendMessage: (query: string, files?: IMessageFile[]) => void;- retryMessage: () => void;- stopGenerating: () => void;- clearChatSession: () => Promise<void>;-- // Model override (temporary, not saved to agent config)- modelOverride: string | null;- setModelOverride: (model: string | null) => void;-}--const ChatContext = createContext<ChatContextType | undefined>(undefined);--/**- * Hook to use the chat context- * @throws {Error} If used outside of ChatProvider- */-// eslint-disable-next-line react-refresh/only-export-components-export const useChatContext = () => {- const context = useContext(ChatContext);- if (!context) throw new Error('useChatContext must be used within a ChatProvider');- return context;-};+import {+ useAgentSettings,+ useAttachments,+ useChat,+ useCreateChatMutation,+ useScrollToBottom,+ useUpdateAgentSettingsMutation,+} from '@react/features/ai-chat/hooks';+import { ChatInputRef, IChildren } from '@react/features/ai-chat/types/chat.types';+import { useAgent } from '@react/shared/hooks/agent';+import { Observability } from '@shared/observability';+import { EVENTS } from '@shared/posthog/constants/events';+import { ChatContext, IChatContext } from '@src/react/features/ai-chat/contexts/chat';+import { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useNavigate, useParams } from 'react-router-dom';++export const ChatContextProvider: FC<IChildren> = ({ children }) => {+ const params = useParams<{ agentId: string }>();+ const agentId = params?.agentId;++ const inputRef = useRef<ChatInputRef>(null);+ const containerRef = useRef<HTMLDivElement>(null);++ const navigate = useNavigate();++ // Internal refs for tracking state+ const isFirstMessageSentRef = useRef(false);+ 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,+ retry: false,+ onError: () => navigate('/error/403'),+ });++ const { data: settingsData, isLoading: isAgentSettingsLoading } = useAgentSettings(agentId);+ const { mutateAsync: createChat, isPending: isChatCreating } = useCreateChatMutation();+ const { mutateAsync: updateAgentSettings } = useUpdateAgentSettingsMutation();++ const agentSettings = settingsData?.settings;++ // ============================================================================+ // FILE UPLOAD MANAGEMENT+ // ============================================================================++ const files = useAttachments({ agentId, chatId: agentSettings?.lastConversationId });++ // ============================================================================+ // SCROLL BEHAVIOR+ // ============================================================================++ const scroll = useScrollToBottom(containerRef);++ // ============================================================================+ // CHAT STATE MANAGEMENT+ // ============================================================================++ const {+ messages,+ 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+ });++ // ============================================================================+ // CHAT ACTIONS+ // ============================================================================++ /**+ * Sends a message with optional file attachments+ * Integrates with the file upload system+ */+ const sendMessage = useCallback(+ async (message: string) => {+ if (!message.trim() && files.data.length === 0) return;-type ChatProviderProps = PropsWithChildren<{ value: ChatContextType }>;+ 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);-/**- * Provider component that wraps your app and makes chat context available to any- * child component that calls useChatContext().- */-export const ChatProvider: FC<ChatProviderProps> = ({ children, value }) => (- <ChatContext.Provider value={value}>{children}</ChatContext.Provider>-);+ // Clear files after successful send+ files.clearFiles();+ } catch (error) {+ console.error('Failed to send message:', error); // eslint-disable-line no-console+ }+ },+ [files, sendChatMessage],+ );++ /**+ * Creates a new chat session/conversation+ */+ const createSession = useCallback(async () => {+ try {+ const conversation = await createChat({+ conversation: {+ summary: '',+ chunkSize: 100,+ lastChunkID: '0',+ label: 'New Chat',+ aiAgentId: agentId,+ },+ });++ await updateAgentSettings({+ agentId,+ settings: { key: 'lastConversationId', value: conversation?.id },+ });+ } catch (error) {+ console.error('Error creating chat session', error); // eslint-disable-line no-console+ }+ }, [agentId, createChat, updateAgentSettings]);++ /**+ * Clears current chat session and creates a new one+ */+ const resetSession = useCallback(async () => {+ stopGenerating();+ isFirstMessageSentRef.current = false;+ clearMessages();+ files.clearFiles();+ 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, clearMessages, files, stopGenerating, 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++ /**+ * 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 || isProcessing;+ if (!isAgentLoading && !inputDisabled) inputRef.current?.focus();+ }, [isAgentLoading, isChatCreating, isProcessing]);++ // Memoize the store to avoid unnecessary re-renders+ const values: IChatContext = useMemo(+ () => ({+ ref: { input: inputRef, container: containerRef },+ agent: {+ data: agent,+ settings: agentSettings,+ isLoading: { agent: isAgentLoading, settings: isAgentSettingsLoading },+ },+ files,+ chat: {+ isChatCreating,+ messages,+ isStreaming,+ isProcessing,+ createSession,+ sendMessage,+ retryMessage,+ stopGenerating,+ clearMessages,+ resetSession,+ },++ scroll,++ modelOverride,+ setModelOverride,+ }),+ [+ inputRef,+ containerRef,+ agent,+ agentSettings,+ isAgentLoading,+ isAgentSettingsLoading,+ files,++ isChatCreating,+ messages,+ isStreaming,+ isProcessing,+ createSession,+ sendMessage,+ retryMessage,+ stopGenerating,+ clearMessages,+ resetSession,++ scroll,++ modelOverride,+ setModelOverride,+ ],+ );++ return <ChatContext.Provider value={values}>{children}</ChatContext.Provider>;+};diff --git a/packages/app/src/react/features/ai-chat/hooks/index.ts b/packages/app/src/react/features/ai-chat/hooks/index.tsindex f7f572ae..718b6bb5 100644--- a/packages/app/src/react/features/ai-chat/hooks/index.ts+++ b/packages/app/src/react/features/ai-chat/hooks/index.ts@@ -1,11 +1,9 @@-export * from './agent-settings';-export * from './use-agent-chat-context';+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-create-chat';+export * from './use-chat-mutation';export * from './use-drag-and-drop';-export * from './use-fileupload';-export * from './use-scroll-to-bottom';+export * from './use-scroll';export * from './use-store';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.tsdeleted file mode 100644index 54d7fb3a..00000000--- a/packages/app/src/react/features/ai-chat/hooks/use-agent-chat-context.ts+++ /dev/null@@ -1,353 +0,0 @@-import { MutableRefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { useNavigate } from 'react-router-dom';--import {- useAgentSettings,- useCreateChatMutation,- useFileUpload,- useUpdateAgentSettingsMutation,-} from '@react/features/ai-chat/hooks';-import { useChat } from '@react/features/ai-chat/hooks/use-chat';-import { ChatInputRef, IChatMessage, IMessageFile } from '@react/features/ai-chat/types/chat.types';-import { useAgent } from '@react/shared/hooks/agent';-import { Observability } from '@shared/observability';-import { EVENTS } from '@shared/posthog/constants/events';--/**- * Configuration options for useAgentChatContext hook- */-export interface IUseAgentChatContextConfig {- agentId: string; // Agent ID for the chat session- inputRef?: MutableRefObject<ChatInputRef>; // Ref to the chat input-}--/**- * Return type for useAgentChatContext hook- */-/* eslint-disable no-unused-vars */-export interface IUseAgentChatContextReturn {- chatContextValue: {- files: IMessageFile[];- uploadingFiles: Set<string>;- isUploadInProgress: boolean;- isMaxFilesUploaded: boolean;- handleFileChange: (e: React.ChangeEvent<HTMLInputElement>) => void;- handleFileDrop: (files: File[]) => Promise<void>;- removeFile: (fileKey: number) => void;- clearFiles: () => void;- uploadError: { show: boolean; message: string };- clearError: () => void;- // Chat state- isGenerating: boolean;- isInputProcessing: boolean;- isRetrying: boolean;- messagesHistory: IChatMessage[];- inputPlaceholder: string;- inputDisabled: boolean;- // Chat actions- sendMessage: (message: string) => Promise<void>;- retryMessage: () => void;- stopGenerating: () => void;- clearChatSession: () => Promise<void>;- // Model override (temporary, not saved to agent config)- modelOverride: string | null;- setModelOverride: (model: string | null) => void;- };- agent: ReturnType<typeof useAgent>['data'];- agentSettings: ReturnType<typeof useAgentSettings>['data'];- isLoading: { agent: boolean; settings: boolean; chatCreating: boolean };- sharedMessagesHistory: IChatMessage[];- handleFileDrop: (files: File[]) => Promise<void>;-}--/**- * Custom hook that encapsulates all Agent Chat context logic- *- * This hook provides:- * - Complete chat state management- * - File upload handling- * - Agent settings management- * - Chat session lifecycle- * - Clean context value for ChatProvider- *- * @param config - Configuration options- * @returns Chat context value and related state- *- * @example- * ```tsx- * const { chatContextValue, agent, isLoading } = useAgentChatContext({- * agentId: '123',- * inputRef: chatInputRef,- * });- *- * return (- * <ChatProvider value={chatContextValue}>- * <YourChatUI />- * </ChatProvider>- * );- * ```- */-export const useAgentChatContext = (- config: IUseAgentChatContextConfig,-): IUseAgentChatContextReturn => {- const { agentId, inputRef } = config;- const navigate = useNavigate();-- // Internal refs for tracking state- const isFirstMessageSentRef = useRef(false);- 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,- retry: false,- onError: () => navigate('/error/403'),- });-- const { data: settingsData, isLoading: isAgentSettingsLoading } = useAgentSettings(agentId);- const { mutateAsync: createChat, isPending: isChatCreating } = useCreateChatMutation();- const { mutateAsync: updateAgentSettings } = useUpdateAgentSettingsMutation();-- const agentSettings = settingsData?.settings;-- // ============================================================================- // FILE UPLOAD MANAGEMENT- // ============================================================================-- const {- files,- uploadingFiles,- uploadError,- handleFileChange,- handleFileDrop,- removeFile,- clearError,- isUploadInProgress,- clearFiles,- } = useFileUpload({ agentId, chatId: agentSettings?.lastConversationId });-- // ============================================================================- // CHAT STATE MANAGEMENT- // ============================================================================-- const {- isStreaming,- stopGenerating,- retryMessage,- messages: messagesHistory,- sendMessage: sendChatMessage,- isProcessing: isInputProcessing,- clearMessages,- } = 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- });-- // ============================================================================- // COMPUTED VALUES- // ============================================================================-- const inputDisabled = isChatCreating || isAgentLoading || isInputProcessing;- const queryInputPlaceholder = agent ? `Message ${agent.name}...` : 'Message ...';- const isMaxFilesUploaded = files.length >= 10;-- // ============================================================================- // CHAT ACTIONS- // ============================================================================-- /**- * Sends a message with optional file attachments- * Integrates with the file upload system- */- const sendMessage = useCallback(- async (message: string) => {- if (!message.trim() && files.length === 0) return;-- try {- // Send message with already-uploaded files- const filesForChat =- files.length > 0- ? (files as unknown as Parameters<typeof sendChatMessage>[1])- : undefined;- await sendChatMessage(message, filesForChat);-- // Clear files after successful send- clearFiles();- } catch (error) {- console.error('Failed to send message:', error); // eslint-disable-line no-console- }- },- [sendChatMessage, files, clearFiles],- );-- /**- * Creates a new chat session/conversation- */- const createNewChatSession = useCallback(async () => {- try {- const conversation = await createChat({- conversation: {- summary: '',- chunkSize: 100,- lastChunkID: '0',- label: 'New Chat',- aiAgentId: agentId,- },- });-- await updateAgentSettings({- agentId,- settings: { key: 'lastConversationId', value: conversation?.id },- });- } catch (error) {- console.error('Error creating chat session', error); // eslint-disable-line no-console- }- }, [agentId, createChat, updateAgentSettings]);-- /**- * Clears current chat session and creates a new one- */- const clearChatSession = useCallback(async () => {- stopGenerating();- isFirstMessageSentRef.current = false;- clearMessages();- clearFiles();- await createNewChatSession();-- // Trigger callback- inputRef?.current?.focus();-- // Track observability events- Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);- Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);- }, [createNewChatSession, clearMessages, clearFiles, stopGenerating, 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;- createNewChatSession().then(() => inputRef?.current?.focus());- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [agentSettings, agent, agentId]); // Only depend on core values, not callbacks-- /**- * Track chat session lifecycle for observability- */- useEffect(() => {- Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);- return () => Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);- }, []);-- // ============================================================================- // CONTEXT VALUE ASSEMBLY (Memoized for Performance)- // ============================================================================-- /**- * Memoized context value to prevent unnecessary re-renders- * Only recreates when dependencies actually change- * This is critical for performance in long conversations- */- const chatContextValue = useMemo(- () => ({- // File handling- files,- uploadingFiles,- isUploadInProgress,- isMaxFilesUploaded,- handleFileChange,- handleFileDrop,- removeFile,- clearFiles,- uploadError,- clearError,-- // Chat state- isGenerating: isStreaming,- isInputProcessing,- isRetrying: false, // Not implemented in new hook yet- messagesHistory,- inputPlaceholder: queryInputPlaceholder,- inputDisabled,-- // Chat actions- sendMessage,- retryMessage,- stopGenerating,- clearChatSession,-- // Model override (temporary, not saved to agent config)- modelOverride,- setModelOverride,- }),- [- // File handling dependencies- files,- uploadingFiles,- isUploadInProgress,- isMaxFilesUploaded,- handleFileChange,- handleFileDrop,- removeFile,- clearFiles,- uploadError,- clearError,- // Chat state dependencies- isStreaming,- isInputProcessing,- messagesHistory,- queryInputPlaceholder,- inputDisabled,- // Chat action dependencies- sendMessage,- retryMessage,- stopGenerating,- clearChatSession,- // Model override dependencies- modelOverride,- setModelOverride,- ],- );-- // ============================================================================- // RETURN VALUE- // ============================================================================-- return {- chatContextValue,- agent,- agentSettings: settingsData,- isLoading: {- agent: isAgentLoading,- settings: isAgentSettingsLoading,- chatCreating: isChatCreating,- },- sharedMessagesHistory: messagesHistory,- handleFileDrop,- };-};diff --git a/packages/app/src/react/features/ai-chat/hooks/agent-settings.ts b/packages/app/src/react/features/ai-chat/hooks/use-agent-settings.tssimilarity index 64%rename from packages/app/src/react/features/ai-chat/hooks/agent-settings.tsrename to packages/app/src/react/features/ai-chat/hooks/use-agent-settings.tsindex 0d719b36..b0d58998 100644--- a/packages/app/src/react/features/ai-chat/hooks/agent-settings.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-agent-settings.ts@@ -1,14 +1,6 @@-/*-============= Hook usage ===============-const { data, error, isLoading, refetch, invalidate, setData } = useAgentSettings(agentId, {- refetchOnWindowFocus: false,- You can pass all the options supported by useQuery here-});-*/-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';-import { deleteAgentSettings, updateAgentSettings } from '@react/features/ai-chat/clients';+import { updateAgentSettings } from '@react/features/ai-chat/clients';import { TUAgentSettings } from '@react/features/ai-chat/types/chat.types';import { AgentSettings } from '@react/shared/types/agent-data.types';@@ -49,16 +41,3 @@ export const useUpdateAgentSettingsMutation = () => {},);};--export const useDeleteAgentSettingsMutation = () => {- const queryClient = useQueryClient();-- return useMutation(- (params: { agentId: string; key: string }) => deleteAgentSettings(params.agentId, params.key),- {- onSuccess: (_, variables) => {- queryClient.invalidateQueries(['agent_settings', variables.agentId]);- },- },- );-};diff --git a/packages/app/src/react/features/ai-chat/hooks/use-create-chat.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-mutation.tssimilarity index 100%rename from packages/app/src/react/features/ai-chat/hooks/use-create-chat.tsrename to packages/app/src/react/features/ai-chat/hooks/use-chat-mutation.tsdiff --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 34742b5e..bf8a90d3 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@@ -5,6 +5,8 @@* 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,@@ -12,8 +14,6 @@ import {IUseChatReturn,} from '@react/features/ai-chat/types/chat.types';import { useCallback, useRef, useState } from 'react';-import { USER_STOPPED_MESSAGE } from '../constants';-import { useChatStream } from './use-chat-stream';/*** Hook configuration interfacediff --git a/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts b/packages/app/src/react/features/ai-chat/hooks/use-fileupload.tsdeleted file mode 100644index 61f86468..00000000--- a/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts+++ /dev/null@@ -1,200 +0,0 @@-/* eslint-disable no-unused-vars */-import { ChangeEvent, 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,- validateSingleFile,-} from '@react/features/ai-chat/utils/file';--interface FileUploadError {- show: boolean;- message: string;-}--interface UseFileUploadReturn {- files: IMessageFile[];- uploadingFiles: Set<string>;- uploadError: FileUploadError;- handleFileChange: (e: ChangeEvent<HTMLInputElement>) => Promise<void>;- handleFileDrop: (droppedFiles: File[]) => Promise<void>;- removeFile: (index: number) => Promise<void>;- clearError: () => void;- isUploadInProgress: boolean;- clearFiles: () => void;-}--// Helper function to generate a unique ID for each file-const generateUniqueFileId = (file: File): string => {- return `${file.name}-${file.size}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;-};--export const useFileUpload = (params?: {- agentId?: string;- chatId?: string;-}): UseFileUploadReturn => {- 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: '' });-- const isUploadInProgress = uploadingFiles.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 (uploadError.show) {- timeoutId = setTimeout(() => {- setUploadError({ show: false, message: '' });- }, 5000);- }- return () => {- if (timeoutId) clearTimeout(timeoutId);- };- }, [uploadError.show]);-- const clearError = useCallback(() => setUploadError({ show: false, message: '' }), []);- const clearFiles = useCallback(() => setFiles([]), []);-- const processFiles = useCallback(- async (newFiles: File[]) => {- const remainingSlots = FILE_LIMITS.MAX_ATTACHED_FILES - files.length;-- if (remainingSlots <= 0) {- setUploadError({- show: true,- message: `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) {- setUploadError({- show: true,- message: invalidFiles[0].error || 'Failed to upload file',- });- }-- if (validFiles.length > 0) {- const filesToUpload = validFiles.slice(0, remainingSlots);-- if (validFiles.length > remainingSlots) {- setUploadError({- show: true,- message: `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));- setUploadingFiles((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));- setUploadError({- show: true,- message: error instanceof Error ? error.message : 'Failed to upload file',- });- } finally {- setUploadingFiles((prev) => {- const next = new Set(prev);- next.delete(id);- return next;- });- }- });-- await Promise.all(uploadPromises);- }- },- [files.length, agentId, chatId, chatClient],- );-- const handleFileChange = useCallback(- async (e: ChangeEvent<HTMLInputElement>) => {- if (!e.target.files?.length) return;- await processFiles(Array.from(e.target.files));- },- [processFiles],- );-- const handleFileDrop = useCallback(- async (droppedFiles: File[]) => {- if (droppedFiles.length > 0) await processFiles(droppedFiles);- },- [processFiles],- );-- 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,- uploadingFiles,- uploadError,- handleFileChange,- handleFileDrop,- removeFile,- clearError,- isUploadInProgress,- clearFiles,- };-};diff --git a/packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.ts b/packages/app/src/react/features/ai-chat/hooks/use-scroll.tssimilarity index 100%rename from packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.tsrename to packages/app/src/react/features/ai-chat/hooks/use-scroll.tsdiff --git a/packages/app/src/react/features/ai-chat/hooks/use-store.tsx b/packages/app/src/react/features/ai-chat/hooks/use-store.tsxindex 6a781fdf..f745b7bf 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-store.tsx+++ b/packages/app/src/react/features/ai-chat/hooks/use-store.tsx@@ -1,4 +1,4 @@-import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat-context';+import { ChatContext, IChatContext } from '@src/react/features/ai-chat/contexts/chat';import { useContext } from 'react';export const useChatStores = () => useContext(ChatContext);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 b5fc5c64..76e653e0 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,5 +1,5 @@import { ChatHeader, Chats, Container, Footer } from '@react/features/ai-chat/components';-import { ChatContextProvider } from '@react/features/ai-chat/contexts/index.new';+import { ChatContextProvider } from '@react/features/ai-chat/contexts';import { memo } from 'react';const AgentChatPage = () => {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 264140a9..007cd46d 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@@ -2,6 +2,8 @@// CORE MESSAGE TYPES// ============================================================================+export type IChildren = { children: React.ReactNode };+/*** Message type discriminator* Complete state representation through type alone