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 API Client and Related Components
Salman-Ahamed66dd3fb44773
diff --git a/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts b/packages/app/src/react/features/ai-chat/clients/chat-api.client.tsindex 67f1a3f8..1e79a169 100644--- a/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts+++ b/packages/app/src/react/features/ai-chat/clients/chat-api.client.ts@@ -12,14 +12,7 @@ import {IStreamConfig,} from '@react/features/ai-chat/types/chat.types';import { performanceMonitor } from '@react/features/ai-chat/utils/chat-performance-monitor';-import {- createThinkingManager,- extractFunctionName,- formatFunctionName,- formatStatusMessage,- processStreamChunk,- splitJSONStream,-} from '@react/features/ai-chat/utils/stream.utils';+import { processStreamChunk, splitJSONStream } from '@react/features/ai-chat/utils/stream.utils';import { CreateChatRequest } from '@react/shared/types/api-payload.types';import { CreateChatsResponse } from '@react/shared/types/api-results.types';@@ -37,7 +30,7 @@ const DEFAULT_CONFIG: IAPIConfig = {*/export class ChatAPIClient {private config: IAPIConfig;- private thinkingManager = createThinkingManager();+ // private thinkingManager = createThinkingManager();/*** Creates a new ChatAPIClient instance@@ -83,7 +76,7 @@ export class ChatAPIClient {*/async streamChat(streamConfig: IStreamConfig, callbacks: IStreamCallbacks): Promise<void> {const { agentId, chatId, message, modelId, attachments, signal, headers = {} } = streamConfig;- const { onContent, onThinking, onToolCall, onDebug, onError, onStart, onComplete } = callbacks;+ const { onContent, onMetaMessages, onError, onStart, onComplete } = callbacks;// Validate required parameters// Message can be empty if attachments are provided@@ -98,16 +91,14 @@ export class ChatAPIClient {// State management for stream processinglet accumulatedData = ''; // eslint-disable-line prefer-const- let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;+ let reader: ReadableStreamDefaultReader<Uint8Array<ArrayBufferLike>>;try {// Start performance monitoringperformanceMonitor.startStream();// Notify stream start- if (onStart) {- onStart();- }+ if (onStart) onStart();// Prepare request headers with optional model overrideconst requestHeaders = {@@ -119,10 +110,7 @@ export class ChatAPIClient {...headers,};- const requestBody = {- message,- attachments: attachments || [],- };+ const requestBody = { message, attachments };// Make streaming requestconst response = await fetch(`${this.config.baseUrl}/stream`, {@@ -157,15 +145,10 @@ export class ChatAPIClient {// Process streamawait this.processStream(reader, signal, accumulatedData, {onContent,- onThinking,- onToolCall,- onDebug,+ onMetaMessages,onError,});- // Stream completed successfully- this.thinkingManager.stop();-// End performance monitoringperformanceMonitor.endStream();@@ -174,9 +157,6 @@ export class ChatAPIClient {// Handle different error typesconst chatError = this.handleStreamError(error, signal);- // Stop thinking messages on error- this.thinkingManager.stop();-// End performance monitoring on errorperformanceMonitor.endStream();@@ -208,12 +188,9 @@ export class ChatAPIClient {reader: ReadableStreamDefaultReader<Uint8Array>,signal: AbortSignal,accumulatedData: string,- callbacks: Pick<- IStreamCallbacks,- 'onContent' | 'onThinking' | 'onToolCall' | 'onDebug' | 'onError'- >,+ callbacks: Pick<IStreamCallbacks, 'onContent' | 'onMetaMessages' | 'onError'>,): Promise<void> {- const { onContent, onThinking, onToolCall, onDebug, onError } = callbacks;+ const { onContent, onMetaMessages, onError } = callbacks;const decoder = new TextDecoder();while (true) {@@ -247,13 +224,11 @@ export class ChatAPIClient {performanceMonitor.recordProcessingTime(0, processingTime);}- if (chunks.length === 0) {- continue; // Wait for more complete data- }+ if (chunks.length === 0) continue; // Wait for more complete data// Process each chunkfor (const chunk of chunks) {- await this.processChunk(chunk, { onContent, onThinking, onToolCall, onDebug, onError });+ await this.processChunk(chunk, { onContent, onMetaMessages, onError });}// Clear accumulated data after successful processing@@ -269,12 +244,9 @@ export class ChatAPIClient {*/private async processChunk(chunk: IStreamChunk,- callbacks: Pick<- IStreamCallbacks,- 'onContent' | 'onThinking' | 'onToolCall' | 'onDebug' | 'onError'- >,+ callbacks: Pick<IStreamCallbacks, 'onContent' | 'onMetaMessages' | 'onError'>,): Promise<void> {- const { onContent, onThinking, onToolCall, onDebug, onError } = callbacks;+ const { onContent, onMetaMessages, onError } = callbacks;const processed = processStreamChunk(chunk);// Extract conversation turn ID from chunk@@ -283,8 +255,8 @@ export class ChatAPIClient {// Handle errorsif (processed.hasError) {const error: IChatError = {- message: processed.error || 'Unknown error occurred',type: 'stream',+ message: processed.error || 'Unknown error occurred',conversationTurnId, // Include turn ID in error};onError(error);@@ -292,58 +264,13 @@ export class ChatAPIClient {}// Handle status messages (highest priority)- if (processed.hasStatusMessage && onThinking) {- const formattedStatus = formatStatusMessage(processed.statusMessage || '');- this.thinkingManager.start(- 'status',- (msg, type) => onThinking(msg, type, conversationTurnId), // Pass turn ID- undefined,- formattedStatus,- );+ if (processed.hasMetaMessages && onMetaMessages) {+ onMetaMessages(processed.metaMessages);return;}- // Handle function calls- if (processed.hasFunctionCall) {- const functionName = processed.functionName || 'Unknown';- const formattedName = formatFunctionName(functionName);-- // Notify tool call callback- if (onToolCall && chunk.function_call?.arguments) {- onToolCall(functionName, chunk.function_call.arguments, conversationTurnId); // Pass turn ID- }-- // Start function thinking- if (onThinking) {- this.thinkingManager.start(- 'function',- (msg, type) => onThinking(msg, type, conversationTurnId), // Pass turn ID- formattedName,- );- }- }-- // Handle debug messages- if (processed.hasDebug && onDebug) {- onDebug(chunk);-- // Try to extract function name from debug- const functionName = extractFunctionName(chunk.debug || '');- if (functionName && onThinking) {- const formattedName = formatFunctionName(functionName);- this.thinkingManager.start(- 'function',- (msg, type) => onThinking(msg, type, conversationTurnId), // Pass turn ID- formattedName,- );- }- }-// Handle content (final response)if (processed.hasContent) {- // Stop thinking when content arrives- this.thinkingManager.stop();-// Deliver content with turn IDonContent(processed.content, conversationTurnId);}diff --git a/packages/app/src/react/features/ai-chat/components/chat.tsx b/packages/app/src/react/features/ai-chat/components/chat.tsxindex c2278e34..d00b77cd 100644--- a/packages/app/src/react/features/ai-chat/components/chat.tsx+++ b/packages/app/src/react/features/ai-chat/components/chat.tsx@@ -25,7 +25,7 @@ interface IChatProps extends IChatMessage {* @returns Appropriate message component*/const ChatComponent: FC<IChatProps> = (props) => {- const { type, files, avatar, message, onRetryClick, thinkingMessage, scrollToBottom } = props;+ const { type, files, avatar, message, onRetryClick, scrollToBottom } = props;switch (type) {case 'loading':@@ -37,10 +37,8 @@ const ChatComponent: FC<IChatProps> = (props) => {case 'system':return (<SystemMessage- avatar={avatar}- message={message}typingAnimation- thinkingMessage={thinkingMessage}+ message={message}onTypingComplete={() => scrollToBottom?.()}onTypingProgress={() => scrollToBottom?.()}/>diff --git a/packages/app/src/react/features/ai-chat/components/system-message.tsx b/packages/app/src/react/features/ai-chat/components/system-message.tsxindex 9d309e31..ef2d4a5b 100644--- a/packages/app/src/react/features/ai-chat/components/system-message.tsx+++ b/packages/app/src/react/features/ai-chat/components/system-message.tsx@@ -1,19 +1,12 @@import { FC, useRef } from 'react';-import {- ErrorMessage,- MarkdownRenderer,- ThinkingMessage,- Typewriter,-} from '@react/features/ai-chat/components';+import { ErrorMessage, MarkdownRenderer, Typewriter } from '@react/features/ai-chat/components';interface ISystemMessageProps {message: string;- avatar?: string;isError?: boolean;isRetrying?: boolean;onRetryClick?: () => void;- thinkingMessage?: string;typingAnimation?: boolean;onTypingComplete?: () => void;onTypingProgress?: () => void;@@ -21,12 +14,10 @@ interface ISystemMessageProps {export const SystemMessage: FC<ISystemMessageProps> = (props) => {const {- avatar,message,isError,isRetrying,onRetryClick,- thinkingMessage,onTypingComplete,onTypingProgress,typingAnimation = true,@@ -34,17 +25,14 @@ export const SystemMessage: FC<ISystemMessageProps> = (props) => {const contentRef = useRef<HTMLDivElement>(null);- if (!message && !thinkingMessage) return null; // if message is empty, return null+ if (!message) return null; // if message is empty, return nullreturn (<div className="system-message-bubble relative">{isError ? (<ErrorMessage message={message} onRetryClick={onRetryClick} isRetrying={isRetrying} />) : (- <div- ref={contentRef}- className="chat-rich-text-response space-y-1 rounded-lg px-3 text-[#141414]"- >+ <div ref={contentRef} className="chat-rich-text-response rounded-lg px-3 text-[#141414]">{typingAnimation ? (<Typewritermessage={message}@@ -55,9 +43,6 @@ export const SystemMessage: FC<ISystemMessageProps> = (props) => {) : (<MarkdownRenderer message={message} />)}-- {/* Display thinking message inline if present */}- {thinkingMessage && <ThinkingMessage message={thinkingMessage} avatar={avatar} />}</div>)}</div>diff --git a/packages/app/src/react/features/ai-chat/components/thinking-message.tsx b/packages/app/src/react/features/ai-chat/components/thinking-message.tsxindex be388b0d..1c60bf96 100644--- a/packages/app/src/react/features/ai-chat/components/thinking-message.tsx+++ b/packages/app/src/react/features/ai-chat/components/thinking-message.tsx@@ -25,7 +25,7 @@ const ThinkingMessage: React.FC<ThinkingMessageProps> = ({ message, avatar }) =><style>{blinkAnimation}</style>{/* White rectangular bubble like the image */}- <div className="flex items-center gap-3">+ <div className="flex items-center gap-3 px-3">{/* Avatar inside the bubble */}<div className="flex-shrink-0"><div className="size-6 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden">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 682fda31..63d4bd90 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@@ -151,7 +151,7 @@ export const useAgentChatContext = (chatId: agentSettings?.lastConversationId || '',// Use override if set, otherwise fall back to agent's default modelmodelId: selectedModelOverride || agentSettings?.chatGptModel,- avatar: agent?.aiAgentSettings?.avatar,+ // avatar: agent?.aiAgentSettings?.avatar,onChatComplete: () => {if (!isFirstMessageSentRef.current) {isFirstMessageSentRef.current = true;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.tsindex 5cd67c45..38101422 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-attachments.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-attachments.ts@@ -94,6 +94,10 @@ export const useAttachments = (props: IProps) => {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)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.tsindex a8b267c1..92e64924 100644--- 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.ts@@ -15,7 +15,6 @@ import { useCallback, useRef, useState } from 'react';* Hook configuration interface*/interface IUseChatStreamConfig {- client?: ChatAPIClient; // Chat API client instanceonStreamStart?: () => void; // Called when stream startsonStreamEnd?: () => void; // Called when stream completes}@@ -65,7 +64,7 @@ interface IUseChatStreamReturn {* ```*/export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStreamReturn => {- const { client, onStreamStart, onStreamEnd } = config;+ const { onStreamStart, onStreamEnd } = config;// State managementconst [isStreaming, setIsStreaming] = useState(false);@@ -73,7 +72,7 @@ export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStream// Refs for lifecycle managementconst abortControllerRef = useRef<AbortController | null>(null);- const clientRef = useRef<ChatAPIClient>(client || new ChatAPIClient());+ const apiClient = new ChatAPIClient();/*** Starts a new chat stream@@ -97,9 +96,7 @@ export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStreamsetIsStreaming(true);// Notify start- if (onStreamStart) {- onStreamStart();- }+ if (onStreamStart) onStreamStart();try {// Wrap callbacks to manage lifecycle@@ -120,7 +117,7 @@ export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStream};// Start streaming with abort signal- await clientRef.current.streamChat(+ await apiClient.streamChat({ ...streamConfig, signal: abortController.signal },wrappedCallbacks,);@@ -136,7 +133,7 @@ export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStreamthrow chatError;}},- [onStreamStart, onStreamEnd],+ [onStreamStart, onStreamEnd], // eslint-disable-line react-hooks/exhaustive-deps);/**diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat.tsindex 345f2550..5b55add7 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@@ -1,4 +1,4 @@-/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */+/* eslint-disable no-unused-vars *//*** Professional React hook for complete chat state management@@ -7,14 +7,13 @@import {IChatMessage,- IFileAttachment,IMessageFile,+ IMetaMessages,IUseChatReturn,- TThinkingType,} from '@react/features/ai-chat/types/chat.types';import { useCallback, useRef, useState } from 'react';-import { ChatAPIClient } from '../clients/chat-api.client';import { USER_STOPPED_MESSAGE } from '../constants';+import { formatStatusMessage } from '../utils/stream.utils';import { useChatStream } from './use-chat-stream';/**@@ -24,8 +23,7 @@ interface IUseChatConfig {agentId: string;chatId: string; // Chat/Conversation IDmodelId?: string; // Model ID to override backend model selection- avatar?: string;- client?: ChatAPIClient; // Custom chat API client+ // client?: ChatAPIClient; // Custom chat API clientheaders?: Record<string, string>; // Custom headers for requestsonChatComplete?: (message: string) => void; // Called when chat completes successfullyonError?: (error: Error) => void; // Called when error occurs@@ -67,23 +65,19 @@ interface IUseChatConfig {* ```*/export const useChat = (config: IUseChatConfig): IUseChatReturn => {- const { agentId, chatId, modelId, avatar, client, headers, onChatComplete, onError } = config;+ const { agentId, chatId, modelId, headers, onChatComplete, onError } = config;// State managementconst [messages, setMessages] = useState<IChatMessage[]>([]);const [isProcessing, setIsProcessing] = useState(false);- // Refs for retry functionality- type IFileWithMetadata = { file: File; metadata: { publicUrl?: string; fileType?: string } };- type IFiles = File[] | IFileWithMetadata[];- const lastUserMessageRef = useRef<{ message: string; files?: IFiles } | null>(null);+ const lastUserMessageRef = useRef<{ message: string; files?: IMessageFile[] } | null>(null);// Current AI message being constructedconst currentAIMessageRef = useRef<string>('');// Track if we're in thinking state to create new message afterconst isThinkingRef = useRef<boolean>(false);- const hasThinkingOccurredRef = useRef<boolean>(false);// Track current conversation turn ID for grouping messagesconst currentTurnIdRef = useRef<string | null>(null);@@ -94,146 +88,62 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {// Stream managementconst { isStreaming, error, startStream, abortStream, clearError } = useChatStream({- client,onStreamStart: () => {currentAIMessageRef.current = '';isThinkingRef.current = false;- hasThinkingOccurredRef.current = false;},onStreamEnd: () => setIsProcessing(false),});- /**- * Uploads files and returns attachment metadata- * Skips upload if files already have publicUrl- */- const uploadFiles = useCallback(- async (files: IFiles): Promise<IFileAttachment[]> => {- const clientInstance = client || new ChatAPIClient();-- // Check if files are already uploaded (have metadata with publicUrl)- const filesWithMetadata = files as IFileWithMetadata[];-- 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?: IFiles) => {+ const addUserMessage = useCallback((message: string, files?: IMessageFile[]) => {const userMessage: IChatMessage = {id: Date.now(),message,type: 'user', // Type determines user vs system - no me property needed!timestamp: Date.now(),- files: files?.map((file, index) => {- if ('metadata' in file && 'id' in file) {- return file as IMessageFile;- }- if ('metadata' in file) {- return {- ...(file as { file: File; metadata: { publicUrl?: string; fileType?: string } }),- id: `${Date.now()}-${index}`,- };- }- return {- file: file as File,- metadata: { fileType: (file as File).type, isUploading: false },- id: `${Date.now()}-${index}`,- };- }),+ files: files || [],};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,- conversationTurnId: currentTurnIdRef.current || undefined, // Include turn ID from current turn- message: '',- type: 'loading', // Type determines AI vs user - no me property needed!- avatar,- timestamp: Date.now(),- };-- setMessages((prev) => [...prev, aiMessage]);- }, [avatar]);-- /**- * Updates the current AI message content (optimized with direct mutation)- * @param content - Message content to update- * @param isError - Whether this is an error message- * @param immediate - Force immediate update bypassing throttle- */- const updateAIMessage = useCallback(- (content: string, isError: boolean = false, immediate: boolean = false) => {- setMessages((prev) => {- const lastMessageIndex = prev.length - 1;-- if (- lastMessageIndex >= 0 &&- (prev[lastMessageIndex].type === 'system' || prev[lastMessageIndex].type === 'loading')- ) {- // Optimized: Create new array only with modified last element- // This avoids copying the entire array for long conversations- const newMessages = prev.slice(0, -1);- newMessages.push({- ...prev[lastMessageIndex],- message: content,- type: isError ? 'error' : 'system',- });- return newMessages;- }-- return prev;- });- },- [],- );-- /**- * Updates thinking/status message for current AI response (optimized)+ * Add or update AI message (similar to addMetaMessage pattern)+ * If last message is 'loading' or 'system', updates it; otherwise adds new message+ * @param content - Message content (empty string for new loading message)+ * @param turnId - Optional conversation turn ID*/- const updateThinkingMessage = useCallback((thinkingMessage: string) => {+ const handleAIMessage = useCallback((content: string = '', turnId?: string) => {setMessages((prev) => {- const lastMessageIndex = prev.length - 1;+ const lastMessage = prev[prev.length - 1];- if (lastMessageIndex >= 0 && prev[lastMessageIndex].type === 'system') {- // Optimized: Only update last element without copying entire array+ // If last message is loading or system type, update it instead of adding new+ if (lastMessage && (lastMessage.type === 'system' || lastMessage.type === 'loading')) {+ // Optimized: Create new array only with modified last element+ // This avoids copying the entire array for long conversationsconst newMessages = prev.slice(0, -1);- newMessages.push({ ...prev[lastMessageIndex], thinkingMessage });+ newMessages.push({+ ...lastMessage,+ message: content,+ conversationTurnId: turnId || lastMessage.conversationTurnId,+ type: content ? 'system' : 'loading',+ });return newMessages;}- return prev;+ // Otherwise, add new AI message+ const aiMessage: IChatMessage = {+ id: Date.now() + 1,+ message: content,+ type: content ? 'system' : 'loading',+ timestamp: Date.now(),+ conversationTurnId: turnId || currentTurnIdRef.current || undefined,+ };++ return [...prev, aiMessage];});}, []);@@ -243,7 +153,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {* @param content - Accumulated content* @param turnId - Optional conversation turn ID*/- const throttledUpdateAIMessage = useCallback((content: string, turnId?: string) => {+ const updateStreamingMessage = useCallback((content: string, turnId?: string) => {// Store pending updatependingUpdateRef.current = { content, turnId };@@ -289,12 +199,54 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {}, 16); // 16ms throttle (60fps) - ultra-smooth, matches scroll rate}, []);+ /**+ * Add and update meta messages for current AI response+ */+ const addMetaMessage = useCallback((metaMessages: IMetaMessages) => {+ const formattedStatusMessage = formatStatusMessage(+ metaMessages.statusMessage || metaMessages.title,+ );++ if (!formattedStatusMessage) return;++ setMessages((prev) => {+ const lastMessage = prev[prev.length - 1];++ // If last message is loading or thinking type, update it instead of adding new+ if (lastMessage?.type === 'loading' || lastMessage?.type === 'thinking') {+ return prev.map((msg, index) =>+ index === prev.length - 1+ ? {+ ...msg,+ type: 'thinking',+ message: formattedStatusMessage,+ thinkingMessage: formattedStatusMessage,+ timestamp: Date.now(),+ }+ : msg,+ );+ }++ // Otherwise, add new loading message+ const metaMessage: IChatMessage = {+ id: Date.now() + 2,+ message: formattedStatusMessage,+ thinkingMessage: formattedStatusMessage,+ type: 'thinking',+ timestamp: Date.now(),+ conversationTurnId: currentTurnIdRef.current || undefined,+ };++ return [...prev, metaMessage];+ });+ }, []);+/*** Sends a message to the AI* Accepts either raw File[] or FileWithMetadata[] (already uploaded)*/const sendMessage = useCallback(- async (message: string, files?: IFiles): Promise<void> => {+ async (message: string, files?: IMessageFile[]): Promise<void> => {// Validate inputif (!message.trim() && (!files || files.length === 0)) return;@@ -303,19 +255,12 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {try {setIsProcessing(true);- clearError();-- // Upload files if present- let attachments: IFileAttachment[] = [];- if (files && files.length > 0) {- attachments = await uploadFiles(files);- }// Add user message to UIaddUserMessage(message, files);// Add empty AI message for streaming- addAIMessage();+ handleAIMessage();// Start streamingawait startStream(@@ -324,7 +269,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {chatId,message,modelId, // Pass model ID to override backend model selection- attachments,+ attachments: files ?? [],signal: new AbortController().signal, // Signal managed by useChatStreamheaders,},@@ -338,12 +283,25 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {currentTurnIdRef.current = conversationTurnId;}- // If content comes after thinking, clear thinking message and create new message- if (hasThinkingOccurredRef.current && isThinkingRef.current) {- updateThinkingMessage(''); // Clear thinking message from current message+ // If content comes after thinking, replace thinking message with loading message+ if (isThinkingRef.current) {+ setMessages((prev) => {+ const lastMessageIndex = prev.length - 1;+ if (lastMessageIndex >= 0 && prev[lastMessageIndex].type === 'thinking') {+ // Replace thinking message with loading message+ const newMessages = prev.slice(0, -1);+ newMessages.push({+ ...prev[lastMessageIndex],+ type: 'loading',+ message: '',+ thinkingMessage: undefined,+ });+ return newMessages;+ }+ return prev;+ });isThinkingRef.current = false; // Mark that we've handled the thinking transitioncurrentAIMessageRef.current = ''; // Reset accumulator for new message- addAIMessage(); // Add new AI message for content after thinking}// Accumulate content@@ -351,52 +309,19 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {// Use throttled update for better performance during streaming// This batches rapid chunk updates to reduce re-renders- throttledUpdateAIMessage(currentAIMessageRef.current, conversationTurnId);+ updateStreamingMessage(currentAIMessageRef.current, conversationTurnId);},- onThinking: (thinkingMsg: string, type: TThinkingType, conversationTurnId?: string) => {+ onMetaMessages: (metaMessages: IMetaMessages, conversationTurnId?: string) => {if (conversationTurnId && !currentTurnIdRef.current) {currentTurnIdRef.current = conversationTurnId; // Capture turn ID from thinking messages}// Mark that we're in thinking stateisThinkingRef.current = true;- hasThinkingOccurredRef.current = true;-- // Update thinking message and change type from 'loading' to 'system' to close loading indicator- setMessages((prev) => {- const lastIndex = prev.length - 1;- if (lastIndex >= 0) {- const lastMsg = prev[lastIndex];- // Only update last element without copying entire array- const newMessages = prev.slice(0, -1);- newMessages.push({- ...lastMsg,- thinkingMessage: thinkingMsg,- conversationTurnId: conversationTurnId || lastMsg.conversationTurnId,- // Change type from 'loading' to 'system' to close loading indicator- type: lastMsg.type === 'loading' ? 'system' : lastMsg.type,- });- return newMessages;- }- return prev;- });- },- onToolCall: (- toolName: string,- args: Record<string, unknown>,- conversationTurnId?: string,- ) => {- // Capture turn ID if not set- if (conversationTurnId && !currentTurnIdRef.current) {- currentTurnIdRef.current = conversationTurnId;- }- // 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);++ addMetaMessage(metaMessages);},+onError: (streamError) => {// Handle stream errorsif (streamError.isAborted) {@@ -434,7 +359,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {});} else {// Real error - show error message- updateAIMessage(streamError.message, true);+ handleAIMessage(streamError.message);}// Reset state@@ -452,7 +377,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {// Finalize message with accumulated contentconst finalMessage = currentAIMessageRef.current;- updateAIMessage(finalMessage, false, true); // immediate update+ handleAIMessage(finalMessage); // immediate update// Reset statecurrentAIMessageRef.current = '';@@ -467,8 +392,6 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {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);@@ -479,12 +402,10 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {agentId,chatId,headers,- uploadFiles,addUserMessage,- addAIMessage,- updateAIMessage,- updateThinkingMessage,- throttledUpdateAIMessage,+ handleAIMessage,+ addMetaMessage,+ updateStreamingMessage,startStream,clearError,onChatComplete,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 f159036a..61f86468 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@@ -126,6 +126,10 @@ export const useFileUpload = (params?: {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)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 112d1ca0..0e303071 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@@ -28,7 +28,6 @@ export interface IChatMessage {message: string; // Message contenttype: TMessageType; // Message type - single source of truth for stateconversationTurnId?: string; // Conversation Turn ID- messageId?: string; // Message ID (future)files?: IMessageFile[]; // Attached files (user messages only)avatar?: string; // Avatar URL for system/AI messagesthinkingMessage?: string; // Inline thinking/status message during generation@@ -44,6 +43,10 @@ export interface IChatMessage {export interface IMessageFile {id: string; // Required ID for React keys and trackingfile: File; // The actual File object+ url?: string; // Public URL (stored after upload)+ name?: string; // File name (stored after upload)+ type?: string; // File type/MIME type (stored after upload)+ size?: number; // File size in bytes (stored after upload)metadata: {key?: string;fileType?: string;@@ -63,20 +66,38 @@ export type TUAgentSettings = { key: string; value: string };// STREAMING TYPES// ============================================================================+export interface IFunctionCall {+ name?: string;+ arguments?: Record<string, unknown>;+ topic?: string;+}++export interface IMetaMessages {+ debug: string;+ title: string;+ statusMessage: string;+ function: string;+ callParams: string;+ parameters: Record<string, unknown>;+ functionCall: IFunctionCall;+}+/*** Stream chunk from backend* Only includes actually used properties*/export interface IStreamChunk {conversationTurnId?: string; // Conversation Turn ID- messageId?: string; // Message ID (future)content?: string; // Content chunk for streaming responses+ debugOn?: boolean; // Debug session indicator+ title?: string; // Title of the message+ debug?: string; // Debug informationstatus_message?: string; // Status/thinking message+ callParams?: string; // Call parameters+ parameters?: Record<string, unknown>; // Parametersfunction?: string; // Function/tool name- function_call?: { name?: string; arguments?: Record<string, unknown> };- debug?: string; // Debug information+ function_call?: IFunctionCall; // Function call informationhashId?: string; // Debug tracking hash- debugOn?: boolean; // Debug session indicatorerror?: string; // Error messageisError?: boolean; // Error indicator}@@ -88,7 +109,7 @@ export interface IStreamConfig {chatId: string; // Conversation IDmessage: string; // User message contentmodelId?: string; // Model ID to override backend model selection- attachments?: IFileAttachment[]; // File attachments+ attachments?: IMessageFile[]; // File attachmentssignal: AbortSignal; // Abort signal for cancellationheaders?: Record<string, string>; // Custom headers}@@ -106,13 +127,7 @@ export interface IFileAttachment {/* eslint-disable no-unused-vars */export interface IStreamCallbacks {onContent: (content: string, conversationTurnId?: string) => void;- onThinking?: (message: string, type: TThinkingType, conversationTurnId?: string) => void;- onToolCall?: (- toolName: string,- args: Record<string, unknown>,- conversationTurnId?: string,- ) => void;- onDebug?: (debug: IStreamChunk) => void; // Debug information received+ onMetaMessages?: (metaMessages: IMetaMessages, conversationTurnId?: string) => void;onError: (error: IChatError) => void; // Error occurred - error object now includes conversationTurnIdonStart?: () => void; // Stream startedonComplete: () => void; // Stream completeddiff --git a/packages/app/src/react/features/ai-chat/utils/stream.utils.ts b/packages/app/src/react/features/ai-chat/utils/stream.utils.tsindex 50e90fe4..62d29d8d 100644--- a/packages/app/src/react/features/ai-chat/utils/stream.utils.ts+++ b/packages/app/src/react/features/ai-chat/utils/stream.utils.ts@@ -5,7 +5,11 @@* Updated: callback signatures now include TThinkingType parameter*/-import { IStreamChunk, TThinkingType } from '@react/features/ai-chat/types/chat.types';+import {+ IMetaMessages,+ IStreamChunk,+ TThinkingType,+} from '@react/features/ai-chat/types/chat.types';/*** Function-specific thinking messages that cycle during function execution@@ -157,9 +161,7 @@ export const extractFunctionName = (debugContent: string): string | null => {* ```*/export const formatFunctionName = (functionName: string): string => {- if (!functionName) {- return '';- }+ if (!functionName) return '';// Convert snake_case to Title Casereturn functionName@@ -182,9 +184,7 @@ export const formatFunctionName = (functionName: string): string => {* ```*/export const formatStatusMessage = (statusMessage: string): string => {- if (!statusMessage) {- return '';- }+ if (!statusMessage) return '';let formatted = statusMessage;@@ -226,9 +226,9 @@ export class ThinkingMessageManager {private currentType: TThinkingType | null = null;private currentIndex: number = 0;private intervalId: NodeJS.Timeout | null = null;- private functionName: string = '';+ private toolName: string = '';private statusMessage: string = '';- private callback: ((message: string, type: TThinkingType) => void) | null = null;+ private callback: ((metaMessages: IMetaMessages) => void) | null = null;/*** Starts thinking messages with priority system@@ -236,13 +236,13 @@ export class ThinkingMessageManager {** @param type - Type of thinking message* @param callback - Callback to invoke with updated messages- * @param functionName - Function name for function type+ * @param toolName - Function name for function type* @param statusMessage - Status message for status type*/start(type: TThinkingType,- callback: (message: string, type: TThinkingType) => void,- functionName?: string,+ callback: (metaMessages: IMetaMessages) => void,+ toolName?: string,statusMessage?: string,): void {// Priority system: status > function > general@@ -262,8 +262,8 @@ export class ThinkingMessageManager {this.callback = callback;this.currentIndex = 0;- if (type === 'function' && functionName) {- this.functionName = functionName;+ if (type === 'function' && toolName) {+ this.toolName = toolName;}if (type === 'status' && statusMessage) {this.statusMessage = formatStatusMessage(statusMessage);@@ -271,7 +271,15 @@ export class ThinkingMessageManager {// Show first message immediatelyconst initialMessage = this.getCurrentMessage();- callback(initialMessage, type);+ callback({+ debug: null,+ title: null,+ statusMessage: initialMessage,+ function: this.toolName,+ callParams: null,+ parameters: null,+ functionCall: this.toolName ? { name: this.toolName } : null,+ });// Start interval only for general and function typesif (type !== 'status') {@@ -280,7 +288,15 @@ export class ThinkingMessageManager {this.currentIndex = (this.currentIndex + 1) % this.getMessagesArray().length;const message = this.getCurrentMessage();if (this.callback && this.currentType) {- this.callback(message, this.currentType);+ this.callback({+ debug: null,+ title: null,+ statusMessage: message,+ function: this.toolName,+ callParams: null,+ parameters: null,+ functionCall: this.toolName ? { name: this.toolName } : null,+ });}}, intervalTime);}@@ -296,7 +312,7 @@ export class ThinkingMessageManager {}this.currentType = null;this.currentIndex = 0;- this.functionName = '';+ this.toolName = '';this.statusMessage = '';this.callback = null;}@@ -313,7 +329,7 @@ export class ThinkingMessageManager {const messageTemplate = messages[this.currentIndex];if (this.currentType === 'function') {- return messageTemplate.replace('{functionName}', this.functionName);+ return messageTemplate.replace('{functionName}', this.toolName);}return messageTemplate;@@ -346,13 +362,27 @@ export const processStreamChunk = (chunk: IStreamChunk) => {return {hasContent: Boolean(chunk.content && chunk.content.trim() !== ''),- hasDebug: Boolean(chunk.debug),- hasError: Boolean(chunk.error || chunk.isError),- hasFunctionCall: Boolean(chunk.function_call || chunk.function),- hasStatusMessage: Boolean(chunk.status_message),- functionName: chunk.function || chunk.function_call?.name || null,- statusMessage: chunk.status_message || null,content: chunk.content || '',+ hasMetaMessages: Boolean(+ chunk.debugOn ||+ chunk.debug ||+ chunk.title ||+ chunk.callParams ||+ chunk.parameters ||+ chunk.function ||+ chunk.function_call ||+ chunk.status_message,+ ),+ metaMessages: {+ debug: chunk.debug || null,+ title: chunk.title || chunk.function_call?.name || null,+ callParams: chunk.callParams || null,+ parameters: chunk.parameters || null,+ function: chunk.function || null,+ functionCall: chunk.function_call || null,+ statusMessage: chunk.status_message || null,+ },+ hasError: Boolean(chunk.isError || (errorMessage && errorMessage.trim() !== '')),error: errorMessage || null,};};