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
Add new hooks for chat management and streaming
Salman-Ahamed5f62b8d46a40
diff --git a/packages/app/src/react/features/ai-chat/hooks/index.ts b/packages/app/src/react/features/ai-chat/hooks/index.tsindex e7502892..c7390f36 100644--- a/packages/app/src/react/features/ai-chat/hooks/index.ts+++ b/packages/app/src/react/features/ai-chat/hooks/index.ts@@ -1,8 +1,9 @@export * from './agent-settings';-export * from './use-create-chat';+export * from './use-agent-chat-context';export * from './use-chat-actions';export * from './use-chat-state';export * from './use-chatbot-state';+export * from './use-create-chat';export * from './use-drag-and-drop';export * from './use-fileupload';export * from './use-scroll-behavior';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.tsnew file mode 100644index 00000000..1df433fa--- /dev/null+++ b/packages/app/src/react/features/ai-chat/hooks/use-agent-chat-context.ts@@ -0,0 +1,353 @@+/**+ * Custom hook for Agent Chat Context+ * Separates the chat context logic from the component for better architecture+ *+ * This hook encapsulates all chat-related state and actions, providing a clean+ * interface for the ChatProvider.+ */++import { useCallback, useEffect, useRef } 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 { useAgent } from '@react/shared/hooks/agent';+import {+ FileWithMetadata,+ IChatMessage as SharedIChatMessage,+} from '@react/shared/types/chat.types';+import { Observability } from '@shared/observability';+import { EVENTS } from '@shared/posthog/constants/events';++/**+ * Configuration options for useAgentChatContext hook+ */+export interface IUseAgentChatContextConfig {+ /** Agent ID for the chat session */+ agentId: string;+ /** Callback when chat is ready */+ onChatReady?: () => void;+ /** Callback when chat session is cleared */+ onChatCleared?: () => void;+}++/**+ * Return type for useAgentChatContext hook+ */+/* eslint-disable no-unused-vars */+export interface IUseAgentChatContextReturn {+ /** Chat context value ready to be passed to ChatProvider */+ chatContextValue: {+ // File handling+ files: FileWithMetadata[];+ 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: SharedIChatMessage[];+ inputPlaceholder: string;+ inputDisabled: boolean;+ // Chat actions+ sendMessage: (message: string) => Promise<void>;+ retryLastMessage: () => void;+ stopGenerating: () => void;+ clearChatSession: () => Promise<void>;+ };+ /** Agent data */+ agent: ReturnType<typeof useAgent>['data'];+ /** Agent settings */+ agentSettings: ReturnType<typeof useAgentSettings>['data'];+ /** Loading states */+ isLoading: {+ agent: boolean;+ settings: boolean;+ chatCreating: boolean;+ };+ /** Shared messages history for UI components */+ sharedMessagesHistory: SharedIChatMessage[];+ /** Function to handle file drop in chat area */+ 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',+ * onChatReady: () => console.log('Chat ready!'),+ * });+ *+ * return (+ * <ChatProvider value={chatContextValue}>+ * <YourChatUI />+ * </ChatProvider>+ * );+ * ```+ */+export const useAgentChatContext = (+ config: IUseAgentChatContextConfig,+): IUseAgentChatContextReturn => {+ const { agentId, onChatReady, onChatCleared } = config;+ const navigate = useNavigate();++ // Internal refs for tracking state+ const isFirstMessageSentRef = useRef(false);+ const hasInitializedChatRef = useRef(false);++ // ============================================================================+ // 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 {+ messages: messagesHistory,+ isGenerating,+ isProcessing: isInputProcessing,+ sendMessage: sendChatMessage,+ retryLastMessage,+ stopGenerating,+ clearMessages: clearChatMessages,+ } = useChat({+ agentId,+ chatId: agentSettings?.lastConversationId || '',+ avatar: agent?.aiAgentSettings?.avatar,+ 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; // FILE_LIMITS.MAX_ATTACHED_FILES++ // Convert internal message format to shared format+ const sharedMessagesHistory: SharedIChatMessage[] = messagesHistory.map((msg) => ({+ me: msg.me,+ message: msg.message,+ type: msg.type as 'user' | 'system' | 'thinking',+ avatar: msg.avatar,+ isReplying: msg.isReplying,+ isError: msg.isError,+ files: msg.files as unknown as FileWithMetadata[] | undefined,+ hideMessage: msg.hideMessage,+ thinkingMessage: msg.thinkingMessage,+ }));++ // ============================================================================+ // 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;+ clearChatMessages();+ clearFiles();+ await createNewChatSession();++ // Trigger callback+ onChatCleared?.();++ // Track observability events+ Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);+ Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);+ }, [createNewChatSession, clearChatMessages, clearFiles, stopGenerating, onChatCleared]);++ // ============================================================================+ // LIFECYCLE EFFECTS+ // ============================================================================++ /**+ * Initialize chat session on component mount+ */+ 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(() => {+ onChatReady?.();+ });+ }+ }, [agentSettings, agent, agentId, createNewChatSession, onChatReady]);++ /**+ * 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+ // ============================================================================++ const chatContextValue = {+ // File handling+ files,+ uploadingFiles,+ isUploadInProgress,+ isMaxFilesUploaded,+ handleFileChange,+ handleFileDrop,+ removeFile,+ clearFiles,+ uploadError,+ clearError,++ // Chat state+ isGenerating,+ isInputProcessing,+ isRetrying: false, // Not implemented in new hook yet+ messagesHistory: sharedMessagesHistory,+ inputPlaceholder: queryInputPlaceholder,+ inputDisabled,++ // Chat actions+ sendMessage,+ retryLastMessage,+ stopGenerating,+ clearChatSession,+ };++ // ============================================================================+ // RETURN VALUE+ // ============================================================================++ return {+ chatContextValue,+ agent,+ agentSettings: settingsData,+ isLoading: {+ agent: isAgentLoading,+ settings: isAgentSettingsLoading,+ chatCreating: isChatCreating,+ },+ sharedMessagesHistory,+ handleFileDrop,+ };+};diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-stream.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-stream.tsnew file mode 100644index 00000000..3da06e5c--- /dev/null+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat-stream.ts@@ -0,0 +1,183 @@+/**+ * React hook for managing chat streaming with abort control+ * Provides clean interface for streaming chat responses with lifecycle management+ */++import { useCallback, useRef, useState } from 'react';+import { ChatAPIClient } from '../clients/chat-api.client';+import { IChatError, IChatStreamCallbacks, IChatStreamConfig } from '../types/chat.types';++/**+ * Hook configuration interface+ */+interface IUseChatStreamConfig {+ /** Chat API client instance */+ client?: ChatAPIClient;+ /** Called when stream starts */+ onStreamStart?: () => void;+ /** Called when stream completes */+ onStreamEnd?: () => void;+}++/**+ * Hook return interface+ */+interface IUseChatStreamReturn {+ /** Whether a stream is currently active */+ isStreaming: boolean;+ /** Current error if any */+ error: IChatError | null;+ /** Start a new chat stream */+ startStream: (config: IChatStreamConfig, callbacks: IChatStreamCallbacks) => Promise<void>;+ /** Abort the current stream */+ abortStream: () => void;+ /** Clear error state */+ clearError: () => void;+}++/**+ * Custom hook for managing chat streaming with abort control+ * Handles stream lifecycle, abort signals, and error states+ *+ * @param config - Hook configuration+ * @returns Stream state and control functions+ *+ * @example+ * ```typescript+ * const { isStreaming, startStream, abortStream } = useChatStream({+ * onStreamStart: () => console.log('Stream started'),+ * onStreamEnd: () => console.log('Stream ended'),+ * });+ *+ * // Start streaming+ * await startStream(+ * {+ * agentId: 'agent-123',+ * chatId: 'chat-456',+ * message: 'Hello!',+ * signal: abortController.signal,+ * },+ * {+ * onContent: (content) => console.log(content),+ * onError: (error) => console.error(error),+ * onComplete: () => console.log('Done'),+ * }+ * );+ *+ * // Abort streaming+ * abortStream();+ * ```+ */+export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStreamReturn => {+ const { client, onStreamStart, onStreamEnd } = config;++ // State management+ const [isStreaming, setIsStreaming] = useState(false);+ const [error, setError] = useState<IChatError | null>(null);++ // Refs for lifecycle management+ const abortControllerRef = useRef<AbortController | null>(null);+ const clientRef = useRef<ChatAPIClient>(client || new ChatAPIClient());++ /**+ * Starts a new chat stream+ * Automatically manages abort controller and lifecycle callbacks+ */+ const startStream = useCallback(+ async (streamConfig: IChatStreamConfig, callbacks: IChatStreamCallbacks): Promise<void> => {+ // Abort any existing stream+ if (abortControllerRef.current) {+ abortControllerRef.current.abort();+ }++ // Create new abort controller+ const abortController = new AbortController();+ abortControllerRef.current = abortController;++ // Clear previous error+ setError(null);++ // Set streaming state+ setIsStreaming(true);++ // Notify start+ if (onStreamStart) {+ onStreamStart();+ }++ try {+ // Wrap callbacks to manage lifecycle+ const wrappedCallbacks: IChatStreamCallbacks = {+ ...callbacks,+ onError: (streamError: IChatError) => {+ setError(streamError);+ callbacks.onError(streamError);+ },+ onComplete: () => {+ setIsStreaming(false);+ abortControllerRef.current = null;++ if (onStreamEnd) {+ onStreamEnd();+ }++ callbacks.onComplete();+ },+ };++ // Start streaming with abort signal+ await clientRef.current.streamChat(+ {+ ...streamConfig,+ signal: abortController.signal,+ },+ wrappedCallbacks,+ );+ } catch (streamError) {+ // Handle errors+ const chatError = streamError as IChatError;+ setError(chatError);+ setIsStreaming(false);+ abortControllerRef.current = null;++ if (onStreamEnd) {+ onStreamEnd();+ }++ throw chatError;+ }+ },+ [onStreamStart, onStreamEnd],+ );++ /**+ * Aborts the current stream+ * Safe to call even if no stream is active+ */+ const abortStream = useCallback(() => {+ if (abortControllerRef.current) {+ abortControllerRef.current.abort();+ abortControllerRef.current = null;+ setIsStreaming(false);++ if (onStreamEnd) {+ onStreamEnd();+ }+ }+ }, [onStreamEnd]);++ /**+ * Clears error state+ */+ const clearError = useCallback(() => {+ setError(null);+ }, []);++ return {+ isStreaming,+ error,+ startStream,+ abortStream,+ clearError,+ };+};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.tsnew file mode 100644index 00000000..c41911aa--- /dev/null+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat.ts@@ -0,0 +1,413 @@+/**+ * Professional React hook for complete chat state management+ * Combines streaming, message history, file uploads, and error handling+ */++import { useCallback, useRef, useState } from 'react';+import { ChatAPIClient } from '../clients/chat-api.client';+import {+ IChatFileAttachment,+ IChatMessage,+ IUseChatReturn,+ TThinkingType,+} from '../types/chat.types';+import { useChatStream } from './use-chat-stream';++/**+ * Hook configuration interface+ */+interface IUseChatConfig {+ /** Agent ID */+ agentId: string;+ /** Chat/Conversation ID */+ chatId: string;+ /** Avatar URL for AI messages */+ avatar?: string;+ /** Custom chat API client */+ client?: ChatAPIClient;+ /** Custom headers for requests */+ headers?: Record<string, string>;+ /** Called when chat completes successfully */+ onChatComplete?: (message: string) => void;+ /** Called when error occurs */+ onError?: (error: Error) => void;+}++/**+ * Main chat hook for complete state management+ * Provides all functionality needed for a chat interface+ *+ * @param config - Hook configuration+ * @returns Complete chat state and actions+ *+ * @example+ * ```typescript+ * const {+ * messages,+ * isGenerating,+ * sendMessage,+ * retryLastMessage,+ * stopGenerating,+ * clearMessages,+ * } = useChat({+ * agentId: 'agent-123',+ * chatId: 'chat-456',+ * avatar: '/avatar.png',+ * });+ *+ * // Send a message+ * await sendMessage('Hello, AI!');+ *+ * // Send with files+ * await sendMessage('Analyze these files', [file1, file2]);+ *+ * // Retry last message+ * await retryLastMessage();+ *+ * // Stop generation+ * stopGenerating();+ * ```+ */+export const useChat = (config: IUseChatConfig): IUseChatReturn => {+ const { agentId, chatId, avatar, client, headers, onChatComplete, onError } = config;++ // State management+ const [messages, setMessages] = useState<IChatMessage[]>([]);+ const [isProcessing, setIsProcessing] = useState(false);++ // Refs for retry functionality+ const lastUserMessageRef = useRef<{+ message: string;+ files?: File[] | Array<{ file: File; metadata: { publicUrl?: string; fileType?: string } }>;+ } | null>(null);++ // Current AI message being constructed+ const currentAIMessageRef = useRef<string>('');++ // Stream management+ const { isStreaming, error, startStream, abortStream, clearError } = useChatStream({+ client,+ onStreamStart: () => {+ currentAIMessageRef.current = '';+ },+ onStreamEnd: () => {+ setIsProcessing(false);+ },+ });++ /**+ * Uploads files and returns attachment metadata+ * Skips upload if files already have publicUrl+ */+ const uploadFiles = useCallback(+ async (+ files: File[] | Array<{ file: File; metadata: { publicUrl?: string; fileType?: string } }>,+ ): Promise<IChatFileAttachment[]> => {+ const clientInstance = client || new ChatAPIClient();++ // Check if files are already uploaded (have metadata with publicUrl)+ const filesWithMetadata = files as Array<{+ file: File;+ metadata: { publicUrl?: string; fileType?: string };+ }>;++ if (filesWithMetadata[0] && 'metadata' in filesWithMetadata[0]) {+ // Files are already uploaded, just extract the attachment info+ return filesWithMetadata+ .filter((f) => f.metadata.publicUrl)+ .map((f) => ({+ url: f.metadata.publicUrl || '',+ name: f.file.name,+ type: f.metadata.fileType || f.file.type,+ size: f.file.size,+ }));+ }++ // Files need to be uploaded+ const rawFiles = files as File[];+ const uploadPromises = rawFiles.map((file) => clientInstance.uploadFile(file, agentId));++ try {+ return await Promise.all(uploadPromises);+ } catch (uploadError) {+ throw new Error(+ `Failed to upload files: ${uploadError instanceof Error ? uploadError.message : 'Unknown error'}`,+ );+ }+ },+ [client, agentId],+ );++ /**+ * Adds a user message to the chat+ */+ const addUserMessage = useCallback(+ (+ message: string,+ files?: File[] | Array<{ file: File; metadata: { publicUrl?: string; fileType?: string } }>,+ ) => {+ const userMessage: IChatMessage = {+ id: Date.now(),+ message,+ type: 'user',+ me: true,+ timestamp: Date.now(),+ files: files?.map((file) => {+ if ('metadata' in file) {+ return file as { file: File; metadata: { publicUrl?: string; fileType?: string } };+ }+ return {+ file: file as File,+ metadata: { fileType: (file as File).type, isUploading: false },+ };+ }),+ };++ setMessages((prev) => [...prev, userMessage]);+ },+ [],+ );++ /**+ * Adds an AI message to the chat (initially empty, for streaming)+ */+ const addAIMessage = useCallback(() => {+ const aiMessage: IChatMessage = {+ id: Date.now() + 1,+ message: '',+ type: 'system',+ me: false,+ avatar,+ isReplying: true,+ timestamp: Date.now(),+ };++ setMessages((prev) => [...prev, aiMessage]);+ }, [avatar]);++ /**+ * Updates the current AI message content+ */+ const updateAIMessage = useCallback((content: string, isError: boolean = false) => {+ setMessages((prev) => {+ const updated = [...prev];+ const lastMessageIndex = updated.length - 1;++ if (lastMessageIndex >= 0 && updated[lastMessageIndex].type === 'system') {+ updated[lastMessageIndex] = {+ ...updated[lastMessageIndex],+ message: content,+ isReplying: false,+ isError,+ };+ }++ return updated;+ });+ }, []);++ /**+ * Updates thinking/status message for current AI response+ */+ const updateThinkingMessage = useCallback((thinkingMessage: string) => {+ setMessages((prev) => {+ const updated = [...prev];+ const lastMessageIndex = updated.length - 1;++ if (lastMessageIndex >= 0 && updated[lastMessageIndex].type === 'system') {+ updated[lastMessageIndex] = {+ ...updated[lastMessageIndex],+ thinkingMessage,+ };+ }++ return updated;+ });+ }, []);++ /**+ * Sends a message to the AI+ * Accepts either raw File[] or FileWithMetadata[] (already uploaded)+ */+ const sendMessage = useCallback(+ async (+ message: string,+ files?: File[] | Array<{ file: File; metadata: { publicUrl?: string; fileType?: string } }>,+ ): Promise<void> => {+ // Validate input+ if (!message.trim() && (!files || files.length === 0)) {+ return;+ }++ // Store for retry+ lastUserMessageRef.current = { message, files };++ try {+ setIsProcessing(true);+ clearError();++ // Upload files if present+ let attachments: IChatFileAttachment[] = [];+ if (files && files.length > 0) {+ attachments = await uploadFiles(files);+ }++ // Add user message to UI+ addUserMessage(message, files);++ // Add empty AI message for streaming+ addAIMessage();++ // Start streaming+ await startStream(+ {+ agentId,+ chatId,+ message,+ attachments,+ signal: new AbortController().signal, // Signal managed by useChatStream+ headers,+ },+ {+ onContent: (content: string) => {+ // Accumulate content+ currentAIMessageRef.current += content;+ updateAIMessage(currentAIMessageRef.current);+ },+ onThinking: (thinkingMsg: string, _type: TThinkingType) => {+ // Update thinking message+ updateThinkingMessage(thinkingMsg);+ },+ onToolCall: (toolName: string, args: Record<string, unknown>) => {+ // Log tool calls (can be extended for UI display)+ console.log('Tool call:', toolName, args);+ },+ onDebug: (debug) => {+ // Log debug info (can be extended for debug UI)+ console.log('Debug:', debug);+ },+ onError: (streamError) => {+ // Handle stream errors+ const errorMessage = streamError.isAborted+ ? 'Response generation was cancelled'+ : streamError.message;++ updateAIMessage(errorMessage, true);++ if (onError) {+ onError(new Error(errorMessage));+ }+ },+ onComplete: () => {+ // Finalize message+ const finalMessage = currentAIMessageRef.current;+ updateAIMessage(finalMessage);++ if (onChatComplete) {+ onChatComplete(finalMessage);+ }+ },+ },+ );+ } catch (sendError) {+ const errorMessage =+ sendError instanceof Error ? sendError.message : 'Failed to send message';++ updateAIMessage(errorMessage, true);++ if (onError) {+ onError(sendError instanceof Error ? sendError : new Error(errorMessage));+ }+ } finally {+ setIsProcessing(false);+ }+ },+ [+ agentId,+ chatId,+ headers,+ uploadFiles,+ addUserMessage,+ addAIMessage,+ updateAIMessage,+ updateThinkingMessage,+ startStream,+ clearError,+ onChatComplete,+ onError,+ ],+ );++ /**+ * Retries the last sent message+ */+ const retryLastMessage = useCallback(async (): Promise<void> => {+ if (!lastUserMessageRef.current) {+ return;+ }++ const { message, files } = lastUserMessageRef.current;++ // Remove last two messages (user message and failed AI response)+ setMessages((prev) => prev.slice(0, -2));++ // Resend the message+ await sendMessage(message, files);+ }, [sendMessage]);++ /**+ * Stops the current generation+ */+ const stopGenerating = useCallback(() => {+ abortStream();++ // Mark current message as stopped+ setMessages((prev) => {+ const updated = [...prev];+ const lastMessageIndex = updated.length - 1;++ if (lastMessageIndex >= 0 && updated[lastMessageIndex].type === 'system') {+ updated[lastMessageIndex] = {+ ...updated[lastMessageIndex],+ isReplying: false,+ thinkingMessage: undefined,+ };+ }++ return updated;+ });+ }, [abortStream]);++ /**+ * Clears all messages+ */+ const clearMessages = useCallback(() => {+ setMessages([]);+ lastUserMessageRef.current = null;+ currentAIMessageRef.current = '';+ }, []);++ /**+ * Clears error state+ */+ const clearErrorState = useCallback(() => {+ clearError();+ }, [clearError]);++ return {+ // State+ messages,+ isGenerating: isStreaming,+ isProcessing,+ error,+ isRetrying: false, // Can be implemented if needed+ lastUserMessage: lastUserMessageRef.current?.message || null,++ // Actions+ sendMessage,+ retryLastMessage,+ stopGenerating,+ clearMessages,+ clearError: clearErrorState,+ };+};