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 API for Consistency and Clarity

Salman-Ahamed799230a8c5f3
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 9728a01f..755aeb49 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
@@ -249,14 +249,14 @@ export class ChatAPIClient {
const processed = processStreamChunk(chunk);
// Extract conversation turn ID from chunk
- const conversationTurnId = chunk.conversationTurnId;
+ const turnId = chunk.conversationTurnId;
// Handle errors
if (processed.hasError) {
const error: IChatError = {
type: 'stream',
+ turnId, // Include turn ID in error
message: processed.error || 'Unknown error occurred',
- conversationTurnId, // Include turn ID in error
};
onError(error);
return;
@@ -271,7 +271,7 @@ export class ChatAPIClient {
// Handle content (final response)
if (processed.hasContent) {
// Deliver content with turn ID
- onContent(processed.content, conversationTurnId);
+ onContent(processed.content, turnId);
}
}
diff --git a/packages/app/src/react/features/ai-chat/components/message-turn-group.tsx b/packages/app/src/react/features/ai-chat/components/chats-with-group.tsx
similarity index 94%
rename from packages/app/src/react/features/ai-chat/components/message-turn-group.tsx
rename to packages/app/src/react/features/ai-chat/components/chats-with-group.tsx
index 216a21c2..d957b04e 100644
--- a/packages/app/src/react/features/ai-chat/components/message-turn-group.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chats-with-group.tsx
@@ -1,6 +1,6 @@
/**
* MessageTurnGroup Component (Memoized for Performance)
- * Groups messages by conversationTurnId and provides a single copy button for the entire group
+ * Groups messages by turnId and provides a single copy button for the entire group
*
* Memoization prevents re-rendering of completed conversation turns
* Critical for long conversations with multiple turns
@@ -13,8 +13,8 @@ import { FaCheck, FaRegCopy } from 'react-icons/fa6';
import { IChatMessage } from '@react/features/ai-chat/types/chat.types';
import { Chat } from './chat';
-interface IMessageTurnGroupProps {
- messages: IChatMessage[]; // Messages in this conversation turn (all share same conversationTurnId)
+interface IProps {
+ messages: IChatMessage[]; // Messages in this conversation turn (all share same turnId)
avatar?: string; // Agent avatar URL
onRetryClick?: () => void; // Retry callback for error messages
scrollToBottom: (smooth?: boolean) => void; // eslint-disable-line no-unused-vars
@@ -24,7 +24,7 @@ interface IMessageTurnGroupProps {
* Groups messages from a single conversation turn
* Displays all messages and provides a single copy button for the entire group
*/
-export const MessageTurnGroup: FC<IMessageTurnGroupProps> = memo((props) => {
+export const ChatsTurnGroup: FC<IProps> = memo((props) => {
const { messages, avatar, onRetryClick, scrollToBottom } = props;
const [copied, setCopied] = useState(false);
const groupRef = useRef<HTMLDivElement>(null);
diff --git a/packages/app/src/react/features/ai-chat/components/chats.tsx b/packages/app/src/react/features/ai-chat/components/chats.tsx
index 34caa433..f01ef40c 100644
--- a/packages/app/src/react/features/ai-chat/components/chats.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chats.tsx
@@ -1,5 +1,5 @@
/* eslint-disable no-unused-vars */
-import { Chat, MessageTurnGroup } from '@react/features/ai-chat/components';
+import { Chat, ChatsTurnGroup } from '@react/features/ai-chat/components';
import { useChatContext } from '@react/features/ai-chat/contexts';
import { useDragAndDrop } from '@react/features/ai-chat/hooks';
import { IChatMessage } from '@react/features/ai-chat/types/chat.types';
@@ -44,7 +44,7 @@ export const Chats: FC<IChatsProps> = (props) => {
const { handleScroll, smartScrollToBottom, shouldAutoScroll } = scroll;
const ref = useRef<HTMLDivElement>(null);
- const { retryLastMessage } = useChatContext();
+ const { retryMessage } = useChatContext();
const dropzoneRef = useDragAndDrop({ onDrop: handleFileDrop });
/**
@@ -153,7 +153,7 @@ export const Chats: FC<IChatsProps> = (props) => {
const avatar = agent?.aiAgentSettings?.avatar;
/**
- * Group messages by conversationTurnId (Optimized)
+ * Group messages by turnId (Optimized)
* Uses incremental grouping for better performance with long conversations
* Messages with same turnId are grouped together
* Messages without turnId are treated as individual groups
@@ -171,16 +171,12 @@ export const Chats: FC<IChatsProps> = (props) => {
// Optimized: Process messages in a single pass
for (let i = 0; i < messages.length; i++) {
const message = messages[i];
- const turnId = message.conversationTurnId || null;
+ const turnId = message.turnId || null;
const isUser = message.type === 'user';
// User messages are always individual (not grouped)
if (isUser) {
- groups.push({
- turnId,
- messages: [message],
- isUserMessage: true,
- });
+ groups.push({ turnId, messages: [message], isUserMessage: true });
continue;
}
@@ -192,11 +188,7 @@ export const Chats: FC<IChatsProps> = (props) => {
lastGroup.messages.push(message);
} else {
// Otherwise create new group
- groups.push({
- turnId,
- messages: [message],
- isUserMessage: false,
- });
+ groups.push({ turnId, messages: [message], isUserMessage: false });
}
}
@@ -219,11 +211,12 @@ export const Chats: FC<IChatsProps> = (props) => {
const isLastGroup = groupIndex === groupedMessages.length - 1;
const lastMessageInGroup = group.messages[group.messages.length - 1];
const canRetry = lastMessageInGroup.type === 'error' && isLastGroup;
- const onRetryClick = canRetry ? retryLastMessage : undefined;
+ const onRetryClick = canRetry ? retryMessage : undefined;
// User messages render individually (no grouping)
if (group.isUserMessage) {
const message = group.messages[0];
+
return (
<Chat
key={message.id || groupIndex}
@@ -238,7 +231,7 @@ export const Chats: FC<IChatsProps> = (props) => {
// AI messages with turnId render as a group
if (group.turnId && group.messages.length > 0) {
return (
- <MessageTurnGroup
+ <ChatsTurnGroup
key={group.turnId}
messages={group.messages}
avatar={avatar}
diff --git a/packages/app/src/react/features/ai-chat/components/index.ts b/packages/app/src/react/features/ai-chat/components/index.ts
index ed398285..c15f435e 100644
--- a/packages/app/src/react/features/ai-chat/components/index.ts
+++ b/packages/app/src/react/features/ai-chat/components/index.ts
@@ -10,7 +10,7 @@ export * from './footer';
export * from './header';
export * from './input';
export * from './markdown-renderer';
-export * from './message-turn-group';
+export * from './chats-with-group';
export * from './reply-loader';
export * from './scroll-to-bottom-button';
export * from './send-button';
diff --git a/packages/app/src/react/features/ai-chat/contexts/index.tsx b/packages/app/src/react/features/ai-chat/contexts/index.tsx
index 618bdd3f..eca43903 100644
--- a/packages/app/src/react/features/ai-chat/contexts/index.tsx
+++ b/packages/app/src/react/features/ai-chat/contexts/index.tsx
@@ -22,10 +22,10 @@ interface ChatContextType {
messagesHistory: IChatMessage[];
sendMessage: (query: string, files?: IMessageFile[]) => void;
- retryLastMessage: () => void;
+ retryMessage: () => void;
stopGenerating: () => void;
clearChatSession: () => Promise<void>;
-
+
// Model override (temporary, not saved to agent config)
selectedModelOverride: string | null;
setSelectedModelOverride: (model: string | null) => void;
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.ts
index 63d4bd90..12995703 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
@@ -47,7 +47,7 @@ export interface IUseAgentChatContextReturn {
inputDisabled: boolean;
// Chat actions
sendMessage: (message: string) => Promise<void>;
- retryLastMessage: () => void;
+ retryMessage: () => void;
stopGenerating: () => void;
clearChatSession: () => Promise<void>;
// Model override (temporary, not saved to agent config)
@@ -139,9 +139,9 @@ export const useAgentChatContext = (
// ============================================================================
const {
- isGenerating,
+ isStreaming,
stopGenerating,
- retryLastMessage,
+ retryMessage,
messages: messagesHistory,
sendMessage: sendChatMessage,
isProcessing: isInputProcessing,
@@ -149,9 +149,7 @@ export const useAgentChatContext = (
} = useChat({
agentId,
chatId: agentSettings?.lastConversationId || '',
- // Use override if set, otherwise fall back to agent's default model
- modelId: selectedModelOverride || agentSettings?.chatGptModel,
- // avatar: agent?.aiAgentSettings?.avatar,
+ modelId: selectedModelOverride || agentSettings?.chatGptModel, // Use override if set, otherwise fall back to agent's default model
onChatComplete: () => {
if (!isFirstMessageSentRef.current) {
isFirstMessageSentRef.current = true;
@@ -294,7 +292,7 @@ export const useAgentChatContext = (
clearError,
// Chat state
- isGenerating,
+ isGenerating: isStreaming,
isInputProcessing,
isRetrying: false, // Not implemented in new hook yet
messagesHistory: sharedMessagesHistory,
@@ -303,7 +301,7 @@ export const useAgentChatContext = (
// Chat actions
sendMessage,
- retryLastMessage,
+ retryMessage,
stopGenerating,
clearChatSession,
@@ -324,14 +322,14 @@ export const useAgentChatContext = (
uploadError,
clearError,
// Chat state dependencies
- isGenerating,
+ isStreaming,
isInputProcessing,
sharedMessagesHistory,
queryInputPlaceholder,
inputDisabled,
// Chat action dependencies
sendMessage,
- retryLastMessage,
+ retryMessage,
stopGenerating,
clearChatSession,
// Model override dependencies
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.ts
index 92e64924..310cc0ac 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
@@ -24,10 +24,8 @@ interface IUseChatStreamConfig {
*/
interface IUseChatStreamReturn {
isStreaming: boolean; // Whether a stream is currently active
- error: IChatError | null; // Current error if any
startStream: (config: IStreamConfig, callbacks: IStreamCallbacks) => Promise<void>; // eslint-disable-line no-unused-vars
abortStream: () => void; // Abort the current stream
- clearError: () => void; // Clear error state
}
/**
@@ -68,7 +66,6 @@ export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStream
// State management
const [isStreaming, setIsStreaming] = useState(false);
- const [error, setError] = useState<IChatError | null>(null);
// Refs for lifecycle management
const abortControllerRef = useRef<AbortController | null>(null);
@@ -89,9 +86,6 @@ export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStream
const abortController = new AbortController();
abortControllerRef.current = abortController;
- // Clear previous error
- setError(null);
-
// Set streaming state
setIsStreaming(true);
@@ -102,10 +96,7 @@ export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStream
// Wrap callbacks to manage lifecycle
const wrappedCallbacks: IStreamCallbacks = {
...callbacks,
- onError: (streamError: IChatError) => {
- setError(streamError);
- callbacks.onError(streamError);
- },
+ onError: (streamError) => callbacks.onError(streamError),
onComplete: () => {
setIsStreaming(false);
abortControllerRef.current = null;
@@ -124,7 +115,6 @@ export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStream
} catch (streamError) {
// Handle errors
const chatError = streamError as IChatError;
- setError(chatError);
setIsStreaming(false);
abortControllerRef.current = null;
@@ -150,12 +140,5 @@ export const useChatStream = (config: IUseChatStreamConfig = {}): IUseChatStream
}
}, [onStreamEnd]);
- /**
- * Clears error state
- */
- const clearError = useCallback(() => {
- setError(null);
- }, []);
-
- return { isStreaming, error, startStream, abortStream, clearError };
+ return { isStreaming, startStream, abortStream };
};
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 fbe85517..d5695a98 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
@@ -40,7 +40,7 @@ interface IUseChatConfig {
* messages,
* isGenerating,
* sendMessage,
- * retryLastMessage,
+ * retryMessage,
* stopGenerating,
* clearMessages,
* } = useChat({
@@ -56,7 +56,7 @@ interface IUseChatConfig {
* await sendMessage('Analyze these files', [file1, file2]);
*
* // Retry last message
- * await retryLastMessage();
+ * await retryMessage();
*
* // Stop generation
* stopGenerating();
@@ -85,7 +85,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
const pendingUpdateRef = useRef<{ content: string; turnId?: string } | null>(null);
// Stream management
- const { isStreaming, error, startStream, abortStream, clearError } = useChatStream({
+ const { isStreaming, startStream, abortStream } = useChatStream({
onStreamStart: () => {
currentAIMessageRef.current = '';
isThinkingRef.current = false;
@@ -126,7 +126,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
newMessages.push({
...lastMessage,
message: content,
- conversationTurnId: turnId || lastMessage.conversationTurnId,
+ turnId: turnId || lastMessage.turnId,
type: content ? 'system' : 'loading',
});
return newMessages;
@@ -138,7 +138,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
message: content,
type: content ? 'system' : 'loading',
timestamp: Date.now(),
- conversationTurnId: turnId || currentTurnIdRef.current || undefined,
+ turnId: turnId || currentTurnIdRef.current || undefined,
};
return [...prev, aiMessage];
@@ -173,7 +173,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
const needsUpdate =
lastMsg.type === 'system' ||
lastMsg.type === 'loading' ||
- (turnId && !lastMsg.conversationTurnId);
+ (turnId && !lastMsg.turnId);
if (needsUpdate) {
// Optimized: Only update last element
@@ -181,7 +181,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
newMessages.push({
...lastMsg,
message: pendingContent,
- conversationTurnId: turnId || lastMsg.conversationTurnId,
+ turnId: turnId || lastMsg.turnId,
type: 'system',
});
return newMessages;
@@ -228,7 +228,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
message: metaMessages.title,
timestamp: Date.now(),
metaMessages, // Store full metaMessages object for component
- conversationTurnId: currentTurnIdRef.current || undefined,
+ turnId: currentTurnIdRef.current || undefined,
};
return [...prev, metaMessage];
@@ -288,7 +288,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
...prev[lastMessageIndex],
type: 'loading',
message: '',
- conversationTurnId: turnId || prev[lastMessageIndex].conversationTurnId,
+ turnId: turnId || prev[lastMessageIndex].turnId,
});
return newMessages;
}
@@ -344,6 +344,7 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
message: USER_STOPPED_MESSAGE,
type: 'error', // Show as error/warning style but not an actual error
timestamp: Date.now(),
+ turnId: currentTurnIdRef.current || undefined,
};
updated.push(stopMessage);
@@ -400,7 +401,6 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
addMetaMessage,
updateStreamingMessage,
startStream,
- clearError,
onChatComplete,
onError,
],
@@ -414,15 +414,24 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
const { message, files } = lastUserMessageRef.current;
- // Smart removal: check last message type
+ // Smart removal: find last user message index and remove everything from that point
setMessages((prev) => {
- const lastMsg = prev[prev.length - 1];
+ // Find the index of the last user message
+ let lastUserMessageIndex = -1;
+ for (let i = prev.length - 1; i >= 0; i--) {
+ if (prev[i].type === 'user') {
+ lastUserMessageIndex = i;
+ break;
+ }
+ }
- // If last message is error (user stopped), remove 3 messages: user + AI + error
- // Otherwise remove 2 messages: user + failed AI response
- const messagesToRemove = lastMsg && lastMsg.type === 'error' ? 3 : 2;
+ // If no user message found, don't remove anything
+ if (lastUserMessageIndex === -1) {
+ return prev;
+ }
- return prev.slice(0, -messagesToRemove);
+ // Remove everything from the last user message onwards
+ return prev.slice(0, lastUserMessageIndex);
});
// Resend the message
@@ -471,25 +480,16 @@ export const useChat = (config: IUseChatConfig): IUseChatReturn => {
currentTurnIdRef.current = null;
}, []);
- /**
- * Clears error state
- */
- const clearErrorState = useCallback(() => {
- clearError();
- }, [clearError]);
-
return {
// State
- messages,
- isGenerating: isStreaming,
- isProcessing,
- error,
+ messages, // ✅
+ isStreaming, // ✅
+ isProcessing, // ✅
// Actions
- sendMessage,
- retryLastMessage,
+ sendMessage, // ✅
+ clearMessages, // ✅
+ retryMessage: retryLastMessage,
stopGenerating,
- clearMessages,
- clearError: clearErrorState,
};
};
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 bb4f7c95..2e1c1347 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
@@ -25,9 +25,9 @@ export type TMessageType = 'user' | 'system' | 'thinking' | 'loading' | 'error';
*/
export interface IChatMessage {
id?: string | number; // Unique identifier
+ turnId?: string; // Conversation Turn ID
message: string; // Message content
type: TMessageType; // Message type - single source of truth for state
- conversationTurnId?: string; // Conversation Turn ID
files?: IMessageFile[]; // Attached files (user messages only)
avatar?: string; // Avatar URL for system/AI messages
metaMessages?: IMetaMessages; // Full meta messages object for thinking component
@@ -126,9 +126,9 @@ export interface IFileAttachment {
*/
/* eslint-disable no-unused-vars */
export interface IStreamCallbacks {
- onContent: (content: string, conversationTurnId?: string) => void;
- onMetaMessages?: (metaMessages: IMetaMessages, conversationTurnId?: string) => void;
- onError: (error: IChatError) => void; // Error occurred - error object now includes conversationTurnId
+ onContent: (content: string, turnId?: string) => void;
+ onMetaMessages?: (metaMessages: IMetaMessages, turnId?: string) => void;
+ onError: (error: IChatError) => void; // Error occurred - error object now includes turnId
onStart?: () => void; // Stream started
onComplete: () => void; // Stream completed
}
@@ -142,7 +142,7 @@ export type TErrorType = 'stream' | 'network' | 'abort' | 'system';
export interface IChatError {
message: string; // Error message
type: TErrorType; // Error type
- conversationTurnId?: string; // Conversation turn ID for grouping
+ turnId?: string; // Conversation turn ID for grouping
originalError?: Error | unknown; // Original error object
isAborted?: boolean; // User-initiated abort flag
}
@@ -157,16 +157,14 @@ export interface IChatError {
export interface IUseChatReturn {
// State
messages: IChatMessage[];
- isGenerating: boolean;
+ isStreaming: boolean;
isProcessing: boolean;
- error: IChatError | null;
// Actions
sendMessage: (message: string, files?: File[] | IMessageFile[]) => Promise<void>;
- retryLastMessage: () => Promise<void>;
+ retryMessage: () => Promise<void>;
stopGenerating: () => void;
clearMessages: () => void;
- clearError: () => void;
}
// ============================================================================