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 useChatActions Hook for Enhanced Type Safety and Code Clarity

Salman-Ahamedeb9b52a7758e
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts
index 28fb5e30..4a9cf464 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts
@@ -1,8 +1,8 @@
import { useCallback, useRef, useState } from 'react';
import { CHAT_ERROR_MESSAGE } from '@react/features/ai-chat/constants';
-import { IChatMessage, IMessageFile } from '@react/features/ai-chat/types/chat.types';
import { chatUtils } from '@react/features/ai-chat/utils';
+import { FileWithMetadata, IChatMessage } from '@react/shared/types/chat.types';
interface UseChatActionsProps {
agentId: string;
@@ -16,7 +16,7 @@ interface UseChatActionsReturn {
isGenerating: boolean;
isInputProcessing: boolean;
isRetrying: boolean;
- sendMessage: (message: string, attachedFiles?: IMessageFile[]) => Promise<void>; // eslint-disable-line no-unused-vars
+ sendMessage: (message: string, attachedFiles?: FileWithMetadata[]) => Promise<void>; // eslint-disable-line no-unused-vars
retryLastMessage: () => void;
stopGenerating: () => void;
clearMessages: () => void;
@@ -25,7 +25,7 @@ interface UseChatActionsReturn {
// Interface to store last user message with files
interface LastUserMessage {
message: string;
- attachedFiles?: IMessageFile[];
+ attachedFiles?: FileWithMetadata[];
}
export const useChatActions = ({
@@ -58,7 +58,7 @@ export const useChatActions = ({
}, []);
const sendMessage = useCallback(
- async (message: string, attachedFiles?: IMessageFile[]) => {
+ async (message: string, attachedFiles?: FileWithMetadata[]) => {
if (!message.trim() && (!attachedFiles || attachedFiles.length === 0)) return;
// Store the complete message with files for retry functionality
@@ -71,8 +71,9 @@ export const useChatActions = ({
if (message.trim()) {
setMessagesHistory((prev) => {
const newMessage: IChatMessage = {
+ me: true,
message: message.replace(/\n/g, '\n'),
- type: 'user', // Type determines user vs system
+ type: 'user',
files: attachedFiles,
};
return [...prev, newMessage];
@@ -80,19 +81,23 @@ export const useChatActions = ({
} else if (attachedFiles?.length) {
setMessagesHistory((prev) => {
const newMessage: IChatMessage = {
- message: '', // Empty message - will auto-hide bubble
- type: 'user', // Type determines user vs system
+ me: true,
+ message: '',
+ type: 'user',
files: attachedFiles,
+ hideMessage: true,
};
return [...prev, newMessage];
});
}
- // Add initial AI response message with loading state
+ // Add initial AI response message
const replyMessage: IChatMessage = {
+ me: false,
message: '',
- type: 'loading', // ✅ Type determines loading state
+ type: 'system',
avatar,
+ isReplying: true,
};
setMessagesHistory((prev) => [...prev, replyMessage]);
@@ -134,9 +139,9 @@ export const useChatActions = ({
// Update the system message with final response and error info
const updatedBubbles = [...filteredBubbles];
updatedBubbles[lastSystemMessageIndex].message = value;
- updatedBubbles[lastSystemMessageIndex].type = errorInfo?.isError
- ? 'error'
- : 'system';
+ updatedBubbles[lastSystemMessageIndex].isReplying = false;
+ updatedBubbles[lastSystemMessageIndex].isError = errorInfo?.isError || false;
+ updatedBubbles[lastSystemMessageIndex].hideMessage = false; // Show the message bubble
updatedBubbles[lastSystemMessageIndex].thinkingMessage = undefined; // Clear thinking message
return updatedBubbles;
}
@@ -149,18 +154,18 @@ export const useChatActions = ({
},
onThinking: (thinking) => {
setMessagesHistory((bubbles) => {
- // Find the last system or loading message index
+ // Find the last system message index
const lastSystemIndex =
bubbles
.map((msg, index) => ({ msg, index }))
- .filter(({ msg }) => msg.type === 'system' || msg.type === 'loading')
+ .filter(({ msg }) => msg.type === 'system')
.pop()?.index ?? -1;
if (lastSystemIndex !== -1) {
// Update the existing system message with thinking message instead of creating separate bubble
const updatedBubbles = [...bubbles];
updatedBubbles[lastSystemIndex].thinkingMessage = thinking.message;
- updatedBubbles[lastSystemIndex].type = 'system'; // Change from loading to system
+ updatedBubbles[lastSystemIndex].isReplying = false;
return updatedBubbles;
}
@@ -171,13 +176,10 @@ export const useChatActions = ({
setMessagesHistory((prev) => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
- if (
- lastMessage &&
- (lastMessage.type === 'system' || lastMessage.type === 'loading')
- ) {
+ if (lastMessage && lastMessage.type === 'system') {
// Show initial processing message and loading indicator
lastMessage.message = '';
- lastMessage.type = 'loading'; // Show loading state
+ lastMessage.isReplying = true; // Show loading indicator for system message
}
return newMessages;
});
@@ -196,8 +198,8 @@ export const useChatActions = ({
});
const lastMessage = newMessages[newMessages.length - 1];
- if (lastMessage && lastMessage.type === 'loading') {
- lastMessage.type = 'system'; // Change from loading to system
+ if (lastMessage) {
+ lastMessage.isReplying = false;
}
return newMessages;
});
@@ -213,7 +215,7 @@ export const useChatActions = ({
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage) {
- lastMessage.type = 'system'; // Change from loading to system on abort
+ lastMessage.isReplying = false;
lastMessage.message += '';
}
return newMessages;
@@ -223,8 +225,9 @@ export const useChatActions = ({
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage) {
- lastMessage.type = 'error'; // Set error type
+ lastMessage.isReplying = false;
lastMessage.message = CHAT_ERROR_MESSAGE;
+ lastMessage.isError = true;
}
return newMessages;
});
@@ -249,12 +252,15 @@ export const useChatActions = ({
const newMessages = [...prev];
const lastMessageIndex = newMessages.length - 1;
- if (lastMessageIndex >= 0 && newMessages[lastMessageIndex].type === 'error') {
- // Replace the error message with a new loading message
+ if (lastMessageIndex >= 0 && newMessages[lastMessageIndex].isError) {
+ // Replace the error message with a new AI response message
newMessages[lastMessageIndex] = {
+ me: false,
message: '',
- type: 'loading', // Type determines loading state
+ type: 'system',
avatar,
+ isReplying: true,
+ isError: false,
};
}
@@ -300,9 +306,9 @@ export const useChatActions = ({
// Update the system message with final response and error info
const updatedBubbles = [...filteredBubbles];
updatedBubbles[lastSystemMessageIndex].message = value;
- updatedBubbles[lastSystemMessageIndex].type = errorInfo?.isError
- ? 'error'
- : 'system';
+ updatedBubbles[lastSystemMessageIndex].isReplying = false;
+ updatedBubbles[lastSystemMessageIndex].isError = errorInfo?.isError || false;
+ updatedBubbles[lastSystemMessageIndex].hideMessage = false;
return updatedBubbles;
}
return filteredBubbles;
@@ -314,33 +320,54 @@ export const useChatActions = ({
},
onThinking: (thinking) => {
setMessagesHistory((bubbles) => {
- // Find the last system or loading message index
+ // Find the last system message index
const lastSystemIndex =
bubbles
.map((msg, index) => ({ msg, index }))
- .filter(({ msg }) => msg.type === 'system' || msg.type === 'loading')
+ .filter(({ msg }) => msg.type === 'system')
.pop()?.index ?? -1;
- if (lastSystemIndex !== -1) {
- // Update the existing system message with thinking message
- const updatedBubbles = [...bubbles];
- updatedBubbles[lastSystemIndex].thinkingMessage = thinking.message;
- updatedBubbles[lastSystemIndex].type = 'system'; // Change from loading to system
- return updatedBubbles;
- }
+ // Check if there's already a thinking message after the last system message
+ const thinkingAfterSystem = bubbles
+ .slice(lastSystemIndex + 1)
+ .find((msg) => msg.type === 'thinking');
- return bubbles;
+ if (thinkingAfterSystem) {
+ // Update existing thinking message
+ thinkingAfterSystem.message = thinking.message;
+ return [...bubbles];
+ } else {
+ // Add new thinking message after the last system message
+ const thinkingMessage: IChatMessage = {
+ me: false,
+ message: thinking.message,
+ type: 'thinking',
+ avatar,
+ isReplying: false,
+ };
+
+ const newBubbles = [...bubbles];
+ if (lastSystemIndex !== -1) {
+ // Insert after the last system message
+ newBubbles.splice(lastSystemIndex + 1, 0, thinkingMessage);
+ // Hide the system message when thinking starts
+ newBubbles[lastSystemIndex].hideMessage = true;
+ newBubbles[lastSystemIndex].isReplying = false;
+ } else {
+ // Add at the end if no system message
+ newBubbles.push(thinkingMessage);
+ }
+
+ return newBubbles;
+ }
});
},
onStart: () => {
setMessagesHistory((prev) => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
- if (
- lastMessage &&
- (lastMessage.type === 'system' || lastMessage.type === 'loading')
- ) {
- lastMessage.type = 'loading'; // Show loading state
+ if (lastMessage && lastMessage.type === 'system') {
+ lastMessage.isReplying = true;
}
return newMessages;
});
@@ -351,8 +378,8 @@ export const useChatActions = ({
const filteredMessages = prev.filter((msg) => msg.type !== 'thinking');
const newMessages = [...filteredMessages];
const lastMessage = newMessages[newMessages.length - 1];
- if (lastMessage && lastMessage.type === 'loading') {
- lastMessage.type = 'system'; // Change from loading to system
+ if (lastMessage) {
+ lastMessage.isReplying = false;
}
return newMessages;
});
@@ -368,7 +395,7 @@ export const useChatActions = ({
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage) {
- lastMessage.type = 'system'; // Change from loading to system on abort
+ lastMessage.isReplying = false;
lastMessage.message += '';
}
return newMessages;
@@ -378,8 +405,9 @@ export const useChatActions = ({
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage) {
- lastMessage.type = 'error'; // Set error type
+ lastMessage.isReplying = false;
lastMessage.message = error.error || error.message || CHAT_ERROR_MESSAGE;
+ lastMessage.isError = true;
}
return newMessages;
});
diff --git a/packages/app/src/react/shared/types/chat.types.ts b/packages/app/src/react/shared/types/chat.types.ts
new file mode 100644
index 00000000..8b14b5e8
--- /dev/null
+++ b/packages/app/src/react/shared/types/chat.types.ts
@@ -0,0 +1,29 @@
+export interface FileMetadata {
+ key?: string;
+ publicUrl?: string;
+ fileType?: string;
+ previewUrl?: string;
+ isUploading?: boolean;
+}
+
+export interface FileWithMetadata {
+ file: File;
+ metadata: FileMetadata;
+ id: string;
+}
+
+export interface IChatMessage {
+ me: boolean;
+ message: string;
+ type?: 'user' | 'system' | 'thinking';
+ avatar?: string;
+ isReplying?: boolean;
+ isError?: boolean;
+ isFirstMessage?: boolean;
+ files?: FileWithMetadata[];
+ hideMessage?: boolean;
+ thinkingMessage?: 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
+}