Skip to content

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.

Refactor Chat Components and Types for Enhanced Meta Message Handling

Salman-Ahamed40676a4111c0
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.ts
index 1e79a169..9728a01f 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
@@ -30,7 +30,6 @@ const DEFAULT_CONFIG: IAPIConfig = {
*/
export class ChatAPIClient {
private config: IAPIConfig;
- // private thinkingManager = createThinkingManager();
/**
* Creates a new ChatAPIClient instance
diff --git a/packages/app/src/react/features/ai-chat/components/chat.tsx b/packages/app/src/react/features/ai-chat/components/chat.tsx
index d00b77cd..2847bc6d 100644
--- a/packages/app/src/react/features/ai-chat/components/chat.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chat.tsx
@@ -24,14 +24,14 @@ interface IChatProps extends IChatMessage {
* @param props - Chat message properties
* @returns Appropriate message component
*/
-const ChatComponent: FC<IChatProps> = (props) => {
- const { type, files, avatar, message, onRetryClick, scrollToBottom } = props;
+export const Chat: FC<IChatProps> = memo((props) => {
+ const { type, files, avatar, message, metaMessages, onRetryClick, scrollToBottom } = props;
switch (type) {
case 'loading':
return <ReplyLoader />;
case 'thinking':
- return <ThinkingMessage message={message} avatar={avatar} />;
+ return <ThinkingMessage avatar={avatar} message={message} metaMessages={metaMessages} />;
case 'user':
return <UserMessage message={message} files={files} />;
case 'system':
@@ -48,14 +48,4 @@ const ChatComponent: FC<IChatProps> = (props) => {
default:
return <SystemMessage isError message="Something went wrong!" onRetryClick={onRetryClick} />;
}
-};
-
-/**
- * Memoized Chat component export
- * Only re-renders when message content actually changes
- *
- * Performance Impact:
- * - 100 message conversation: Reduces re-renders from 20,000 to ~200 (99% improvement!)
- * - Smooth streaming even with 500+ messages
- */
-export const Chat = memo(ChatComponent);
+});
diff --git a/packages/app/src/react/features/ai-chat/components/message-turn-group.tsx b/packages/app/src/react/features/ai-chat/components/message-turn-group.tsx
index 654d963f..46306cf2 100644
--- a/packages/app/src/react/features/ai-chat/components/message-turn-group.tsx
+++ b/packages/app/src/react/features/ai-chat/components/message-turn-group.tsx
@@ -10,7 +10,7 @@ import { Tooltip } from 'flowbite-react';
import { FC, memo, useRef, useState } from 'react';
import { FaCheck, FaRegCopy } from 'react-icons/fa6';
-import { IChatMessage } from '../types/chat.types';
+import { IChatMessage } from '@react/features/ai-chat/types/chat.types';
import { Chat } from './chat';
interface IMessageTurnGroupProps {
@@ -40,7 +40,7 @@ const MessageTurnGroupComponent: FC<IMessageTurnGroupProps> = (props) => {
lastMessage &&
lastMessage.type !== 'loading' &&
lastMessage.type !== 'thinking' &&
- !lastMessage.thinkingMessage;
+ !lastMessage.metaMessages;
/**
* Copies all system message content from this group
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.tsx
index 1c60bf96..61c17328 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
@@ -1,8 +1,14 @@
-import React from 'react';
+import { IMetaMessages } from '@react/features/ai-chat/types/chat.types';
+import {
+ createThinkingManager,
+ formatStatusMessage,
+} from '@react/features/ai-chat/utils/stream.utils';
+import { FC, useEffect, useRef, useState } from 'react';
-interface ThinkingMessageProps {
+interface IProps {
message: string;
avatar?: string;
+ metaMessages?: IMetaMessages;
}
// Custom CSS for smooth blinking animation (like the image)
@@ -19,7 +25,42 @@ const blinkAnimation = `
}
`;
-const ThinkingMessage: React.FC<ThinkingMessageProps> = ({ message, avatar }) => {
+/**
+ * ThinkingMessage Component
+ * Manages thinking message cycling internally using ThinkingMessageManager
+ * Receives metaMessages from parent and handles the cycling logic
+ */
+export const ThinkingMessage: FC<IProps> = ({ avatar, metaMessages }) => {
+ const [thinkingMessage, setThinkingMessage] = useState<string>('');
+ const thinkingManagerRef = useRef(createThinkingManager());
+
+ /**
+ * Effect to manage thinking message lifecycle
+ * Starts/updates cycling when metaMessages are received
+ * The ThinkingMessageManager handles priority internally (status > tools > general)
+ * Stops when component unmounts
+ */
+ useEffect(() => {
+ const manager = thinkingManagerRef.current;
+
+ // Check if statusMessage exists - if yes, just display formatted, no cycling
+ if (metaMessages?.statusMessage) {
+ // Format and display statusMessage directly, no thinkingManager needed
+ const formatted = formatStatusMessage(metaMessages.statusMessage);
+ setThinkingMessage(formatted);
+ manager.stop(); // Stop any existing cycling
+ return;
+ }
+
+ // No statusMessage, check for toolName
+ const toolName = metaMessages?.title || metaMessages?.functionCall?.name;
+
+ manager.start(setThinkingMessage, toolName || '');
+
+ // Cleanup: stop thinking manager when component unmounts
+ return () => manager.stop();
+ }, [metaMessages]);
+
return (
<>
<style>{blinkAnimation}</style>
@@ -41,11 +82,11 @@ const ThinkingMessage: React.FC<ThinkingMessageProps> = ({ message, avatar }) =>
{/* Message text inside the bubble */}
<div className="flex-1">
- <span className="text-sm text-gray-500 font-medium smooth-blink-text">{message}</span>
+ <span className="text-sm text-gray-500 font-medium smooth-blink-text">
+ {thinkingMessage}
+ </span>
</div>
</div>
</>
);
};
-
-export { ThinkingMessage };
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.ts
index 5b55add7..43944675 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
@@ -13,7 +13,6 @@ import {
} from '@react/features/ai-chat/types/chat.types';
import { useCallback, useRef, useState } from 'react';
import { USER_STOPPED_MESSAGE } from '../constants';
-import { formatStatusMessage } from '../utils/stream.utils';
import { useChatStream } from './use-chat-stream';
/**
@@ -23,7 +22,6 @@ interface IUseChatConfig {
agentId: string;
chatId: string; // Chat/Conversation ID
modelId?: string; // Model ID to override backend model selection
- // client?: ChatAPIClient; // Custom chat API client
headers?: Record<string, string>; // Custom headers for requests
onChatComplete?: (message: string) => void; // Called when chat completes successfully
onError?: (error: Error) => void; // Called when error occurs
@@ -203,11 +201,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
* Add and update meta messages for current AI response
*/
const addMetaMessage = useCallback((metaMessages: IMetaMessages) => {
- const formattedStatusMessage = formatStatusMessage(
- metaMessages.statusMessage || metaMessages.title,
- );
-
- if (!formattedStatusMessage) return;
+ if (!metaMessages || !metaMessages.title) return;
setMessages((prev) => {
const lastMessage = prev[prev.length - 1];
@@ -219,8 +213,8 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
? {
...msg,
type: 'thinking',
- message: formattedStatusMessage,
- thinkingMessage: formattedStatusMessage,
+ message: metaMessages.title,
+ metaMessages, // Store full metaMessages object for component
timestamp: Date.now(),
}
: msg,
@@ -230,10 +224,10 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
// Otherwise, add new loading message
const metaMessage: IChatMessage = {
id: Date.now() + 2,
- message: formattedStatusMessage,
- thinkingMessage: formattedStatusMessage,
type: 'thinking',
+ message: metaMessages.title,
timestamp: Date.now(),
+ metaMessages, // Store full metaMessages object for component
conversationTurnId: currentTurnIdRef.current || undefined,
};
@@ -277,10 +271,10 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
onStart: () => {
currentTurnIdRef.current = null; // Reset turn ID for new conversation turn
},
- onContent: (content: string, conversationTurnId?: string) => {
+ onContent: (content: string, turnId?: string) => {
// Capture turn ID only once
- if (conversationTurnId && !currentTurnIdRef.current) {
- currentTurnIdRef.current = conversationTurnId;
+ if (turnId && !currentTurnIdRef.current) {
+ currentTurnIdRef.current = turnId;
}
// If content comes after thinking, replace thinking message with loading message
@@ -294,7 +288,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
...prev[lastMessageIndex],
type: 'loading',
message: '',
- thinkingMessage: undefined,
+ conversationTurnId: turnId || prev[lastMessageIndex].conversationTurnId,
});
return newMessages;
}
@@ -309,11 +303,11 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
// Use throttled update for better performance during streaming
// This batches rapid chunk updates to reduce re-renders
- updateStreamingMessage(currentAIMessageRef.current, conversationTurnId);
+ updateStreamingMessage(currentAIMessageRef.current, turnId);
},
- onMetaMessages: (metaMessages: IMetaMessages, conversationTurnId?: string) => {
- if (conversationTurnId && !currentTurnIdRef.current) {
- currentTurnIdRef.current = conversationTurnId; // Capture turn ID from thinking messages
+ onMetaMessages: (metaMessages: IMetaMessages, turnId?: string) => {
+ if (turnId && !currentTurnIdRef.current) {
+ currentTurnIdRef.current = turnId; // Capture turn ID from thinking messages
}
// Mark that we're in thinking state
@@ -340,7 +334,6 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
...lastMsg,
message: currentContent || lastMsg.message,
type: 'system',
- thinkingMessage: undefined,
};
}
}
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.ts
index 0e303071..bb4f7c95 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
@@ -30,7 +30,7 @@ export interface IChatMessage {
conversationTurnId?: string; // Conversation Turn ID
files?: IMessageFile[]; // Attached files (user messages only)
avatar?: string; // Avatar URL for system/AI messages
- thinkingMessage?: string; // Inline thinking/status message during generation
+ metaMessages?: IMetaMessages; // Full meta messages object for thinking component
onRetryClick?: () => void; // Retry callback for error messages
timestamp?: number; // Message timestamp (optional, for future use)
}
@@ -102,7 +102,7 @@ export interface IStreamChunk {
isError?: boolean; // Error indicator
}
-export type TThinkingType = 'general' | 'function' | 'status'; // Thinking message type discriminator
+export type TThinkingType = 'tools' | 'general'; // Thinking message type discriminator
export interface IStreamConfig {
agentId: string; // Target agent ID
diff --git a/packages/app/src/react/features/ai-chat/utils/stream.utils.ts b/packages/app/src/react/features/ai-chat/utils/stream.utils.ts
index 62d29d8d..b0f7ba45 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,11 +5,7 @@
* Updated: callback signatures now include TThinkingType parameter
*/
-import {
- IMetaMessages,
- IStreamChunk,
- TThinkingType,
-} from '@react/features/ai-chat/types/chat.types';
+import { IStreamChunk, TThinkingType } from '@react/features/ai-chat/types/chat.types';
/**
* Function-specific thinking messages that cycle during function execution
@@ -51,14 +47,10 @@ const GENERAL_THINKING_MESSAGES = [
*/
export const splitJSONStream = (data: string): IStreamChunk[] => {
// Handle empty or invalid data
- if (!data || typeof data !== 'string') {
- return [];
- }
+ if (!data || typeof data !== 'string') return [];
const cleanData = data.trim();
- if (!cleanData) {
- return [];
- }
+ if (!cleanData) return [];
// Split by '}{' pattern - common in streaming JSON
const jsonStrings = cleanData
@@ -67,9 +59,7 @@ export const splitJSONStream = (data: string): IStreamChunk[] => {
let cleanStr = str.trim();
// Skip empty strings
- if (!cleanStr) {
- return null;
- }
+ if (!cleanStr) return null;
// Add opening brace if not first element
if (index !== 0 && !cleanStr.startsWith('{')) {
@@ -105,46 +95,6 @@ export const splitJSONStream = (data: string): IStreamChunk[] => {
return parsedChunks;
};
-/**
- * Extracts function name from debug message content
- * Supports multiple debug message formats
- *
- * @param debugContent - Raw debug message content
- * @returns Extracted function name or null
- *
- * @example
- * ```typescript
- * extractFunctionName('[ABC123] Function Call : getUserData');
- * // Returns: 'getUserData'
- *
- * extractFunctionName('Call Response : processPayment');
- * // Returns: 'processPayment'
- * ```
- */
-export const extractFunctionName = (debugContent: string): string | null => {
- if (!debugContent) {
- return null;
- }
-
- // Multiple patterns to extract function name from debug messages
- const patterns = [
- /(?:\[\w+\]\s+Function Call\s*:\s*)([a-zA-Z_][a-zA-Z0-9_]*)/,
- /(?:\[\w+\]\s+Call Response\s*:\s*)([a-zA-Z_][a-zA-Z0-9_]*)/,
- /(?:Function Call\s*:\s*)([a-zA-Z_][a-zA-Z0-9_]*)/,
- /(?:Call Response\s*:\s*)([a-zA-Z_][a-zA-Z0-9_]*)/,
- /^([a-zA-Z_][a-zA-Z0-9_]*)$/, // Just function name alone
- ];
-
- for (const pattern of patterns) {
- const match = debugContent.match(pattern);
- if (match && match[1]) {
- return match[1];
- }
- }
-
- return null;
-};
-
/**
* Formats function name from snake_case to Title Case for display
*
@@ -227,8 +177,7 @@ export class ThinkingMessageManager {
private currentIndex: number = 0;
private intervalId: NodeJS.Timeout | null = null;
private toolName: string = '';
- private statusMessage: string = '';
- private callback: ((metaMessages: IMetaMessages) => void) | null = null;
+ private callback: (message: string) => void;
/**
* Starts thinking messages with priority system
@@ -239,67 +188,30 @@ export class ThinkingMessageManager {
* @param toolName - Function name for function type
* @param statusMessage - Status message for status type
*/
- start(
- type: TThinkingType,
- callback: (metaMessages: IMetaMessages) => void,
- toolName?: string,
- statusMessage?: string,
- ): void {
- // Priority system: status > function > general
- const priorityOrder: Record<TThinkingType, number> = { status: 3, function: 2, general: 1 };
- const currentPriority = this.currentType ? priorityOrder[this.currentType] : 0;
- const newPriority = priorityOrder[type];
-
- // Only start new thinking if it has higher or equal priority
- if (newPriority < currentPriority) {
- return; // Don't override higher priority thinking
- }
-
- // Stop any existing thinking
+ start(callback: (message: string) => void, toolName?: string): void {
+ // Stop any existing thinking before starting new one
this.stop();
- this.currentType = type;
+ this.currentType = toolName ? 'tools' : 'general';
this.callback = callback;
this.currentIndex = 0;
- if (type === 'function' && toolName) {
- this.toolName = toolName;
- }
- if (type === 'status' && statusMessage) {
- this.statusMessage = formatStatusMessage(statusMessage);
+ if (this.currentType === 'tools' && toolName) {
+ this.toolName = formatFunctionName(toolName);
}
// Show first message immediately
const initialMessage = this.getCurrentMessage();
- callback({
- debug: null,
- title: null,
- statusMessage: initialMessage,
- function: this.toolName,
- callParams: null,
- parameters: null,
- functionCall: this.toolName ? { name: this.toolName } : null,
- });
+ callback(initialMessage);
// Start interval only for general and function types
- if (type !== 'status') {
- const intervalTime = type === 'function' ? 5000 : 3000;
- this.intervalId = setInterval(() => {
- this.currentIndex = (this.currentIndex + 1) % this.getMessagesArray().length;
- const message = this.getCurrentMessage();
- if (this.callback && 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);
- }
+
+ const intervalTime = this.currentType === 'tools' ? 5000 : 3000;
+ this.intervalId = setInterval(() => {
+ this.currentIndex = (this.currentIndex + 1) % this.getMessagesArray().length;
+ const message = this.getCurrentMessage();
+ if (this.callback) this.callback(message);
+ }, intervalTime);
}
/**
@@ -313,22 +225,17 @@ export class ThinkingMessageManager {
this.currentType = null;
this.currentIndex = 0;
this.toolName = '';
- this.statusMessage = '';
- this.callback = null;
+ this.callback = () => {};
}
/**
* Gets current message with placeholders replaced
*/
private getCurrentMessage(): string {
- if (this.currentType === 'status') {
- return this.statusMessage;
- }
-
const messages = this.getMessagesArray();
const messageTemplate = messages[this.currentIndex];
- if (this.currentType === 'function') {
+ if (this.currentType === 'tools') {
return messageTemplate.replace('{functionName}', this.toolName);
}
@@ -340,7 +247,7 @@ export class ThinkingMessageManager {
*/
private getMessagesArray(): string[] {
switch (this.currentType) {
- case 'function':
+ case 'tools':
return FUNCTION_THINKING_MESSAGES;
case 'general':
return GENERAL_THINKING_MESSAGES;
diff --git a/packages/app/src/react/shared/types/chat.types.ts b/packages/app/src/react/shared/types/chat.types.ts
index 8b14b5e8..4f1ab318 100644
--- a/packages/app/src/react/shared/types/chat.types.ts
+++ b/packages/app/src/react/shared/types/chat.types.ts
@@ -22,7 +22,7 @@ export interface IChatMessage {
isFirstMessage?: boolean;
files?: FileWithMetadata[];
hideMessage?: boolean;
- thinkingMessage?: string; // Inline thinking message to show with system messages
+ statusMessage?: string; // Inline thinking message to show with system messages
isLast?: boolean; // Whether this is the last message in the chat
isRetrying?: boolean; // Whether this message is being retried
onRetryClick?: () => void; // Function to call when retry is clicked