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.

Add custom hooks for chat state management and file uploads

Salman-Ahameddaf61fff2007
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts
new file mode 100644
index 00000000..029219a6
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts
@@ -0,0 +1,329 @@
+import { ChatAPIClient } from '@react/features/ai-chat/clients/chat-api.client';
+import { MESSAGE_TYPES } from '@react/features/ai-chat/constants';
+import type {
+ IAttachment,
+ IChatError,
+ IChatState,
+ IConfigOptions,
+ IMessage,
+ IMetaMessages,
+} from '@react/features/ai-chat/types/chat';
+import { useCallback, useMemo, useRef, useState } from 'react';
+
+export const useChatState = (options: IConfigOptions): IChatState => {
+ const { agentId, chatId, modelId, enableMetaMessages = false, inputRef } = options;
+
+ const [messages, setMessages] = useState<IMessage[]>([]);
+ const [isStreaming, setIsStreaming] = useState<boolean>(false);
+
+ const abortRef = useRef<AbortController | null>(null);
+ const chatClient = useMemo(() => new ChatAPIClient(), []);
+
+ const onStreamContent = useCallback((content: string): void => {
+ if (!content) return;
+
+ setMessages((prev) => {
+ const updated = [...prev];
+ const lastIdx = updated.length - 1;
+ const lastMessage = updated[lastIdx];
+
+ if (!lastMessage) return prev;
+
+ if (lastMessage.type === MESSAGE_TYPES.LOADING) {
+ updated[lastIdx] = {
+ ...lastMessage,
+ type: MESSAGE_TYPES.SYSTEM,
+ content: content,
+ updatedAt: Date.now(),
+ };
+ return updated;
+ }
+
+ if (lastMessage.type === MESSAGE_TYPES.SYSTEM) {
+ const currentContent = typeof lastMessage.content === 'string' ? lastMessage.content : '';
+ updated[lastIdx] = {
+ ...lastMessage,
+ content: currentContent + content,
+ updatedAt: Date.now(),
+ };
+ return updated;
+ }
+
+ const newMessage: IMessage = {
+ id: Date.now() + Math.random(),
+ type: MESSAGE_TYPES.SYSTEM,
+ content: content,
+ updatedAt: Date.now(),
+ };
+
+ return [...updated, newMessage];
+ });
+ }, []);
+
+ const onMetaMessage = useCallback(
+ (meta: IMetaMessages): void => {
+ if (!enableMetaMessages) return;
+
+ setMessages((prev) => {
+ const updated = [...prev];
+ const lastIdx = updated.length - 1;
+ const lastMessage = updated[lastIdx];
+
+ if (!lastMessage) return prev;
+
+ const debugText = meta.debug?.trim() || '';
+
+ // Convert LOADING to DEBUG
+ if (lastMessage.type === MESSAGE_TYPES.LOADING) {
+ updated[lastIdx] = {
+ ...lastMessage,
+ type: MESSAGE_TYPES.META,
+ content: debugText,
+ metaMessages: meta,
+ updatedAt: Date.now(),
+ };
+ return updated;
+ }
+
+ // Find existing DEBUG message by hashId or title
+ const matchIdx = updated
+ .slice()
+ .reverse()
+ .findIndex((msg) => {
+ if (msg.type !== MESSAGE_TYPES.META) return false;
+
+ const msgHashId = msg.metaMessages?.hashId;
+ const newHashId = meta.hashId;
+ if (msgHashId && newHashId) return msgHashId === newHashId;
+
+ const msgTitle = msg.metaMessages?.title || '';
+ const newTitle = meta.title || '';
+ return msgTitle === newTitle;
+ });
+
+ // Update existing DEBUG message
+ if (matchIdx !== -1) {
+ const realIndex = updated.length - 1 - matchIdx;
+ const target = updated[realIndex];
+
+ const currentContent = Array.isArray(target.content)
+ ? target.content
+ : [target.content].filter(Boolean);
+
+ const updatedContent = debugText
+ ? [...currentContent, debugText].join('\n\n')
+ : currentContent.join('\n\n');
+
+ updated[realIndex] = {
+ ...target,
+ content: updatedContent,
+ metaMessages: {
+ ...target.metaMessages,
+ ...meta,
+ },
+ updatedAt: Date.now(),
+ };
+ return updated;
+ }
+
+ // Create new DEBUG message
+ const newMessage: IMessage = {
+ id: Date.now() + Math.random(),
+ type: MESSAGE_TYPES.META,
+ content: debugText,
+ metaMessages: meta,
+ updatedAt: Date.now(),
+ };
+
+ return [...updated, newMessage];
+ });
+ },
+ [enableMetaMessages],
+ );
+
+ const onStreamError = useCallback((error: IChatError): void => {
+ if (error.isAborted) {
+ setIsStreaming(false);
+ return;
+ }
+
+ setMessages((prev) => {
+ const filtered = prev.filter((msg) => msg.type !== MESSAGE_TYPES.LOADING);
+ const errorMessage: IMessage = {
+ id: Date.now() + Math.random(),
+ type: MESSAGE_TYPES.ERROR,
+ content: error.message || 'An error occurred',
+ updatedAt: Date.now(),
+ };
+ return [...filtered, errorMessage];
+ });
+
+ setIsStreaming(false);
+ }, []);
+
+ const sendMessage = useCallback(
+ async (
+ message: string,
+ currentAttachments: IAttachment[] = [],
+ shouldSetUserMessage = true,
+ ): Promise<void> => {
+ if (isStreaming) return;
+
+ try {
+ setIsStreaming(true);
+ abortRef.current = new AbortController();
+ const now = Date.now();
+
+ setMessages((prev) => {
+ const msgCount = prev.length;
+
+ const userMessage: IMessage | null = shouldSetUserMessage
+ ? {
+ id: msgCount + 1,
+ type: MESSAGE_TYPES.USER,
+ content: message?.trim() || '',
+ attachments:
+ currentAttachments.length > 0
+ ? currentAttachments.map((a) => ({
+ name: a.name,
+ type: a.type,
+ size: a.size,
+ url: a.url,
+ blobUrl: a.blobUrl,
+ file: a.file,
+ }))
+ : undefined,
+ updatedAt: now,
+ }
+ : null;
+
+ const loadingMessage: IMessage = {
+ id: shouldSetUserMessage ? msgCount + 2 : msgCount + 1,
+ type: MESSAGE_TYPES.LOADING,
+ content: '',
+ updatedAt: now,
+ };
+
+ if (shouldSetUserMessage && userMessage) {
+ return [...prev, userMessage, loadingMessage];
+ }
+ return [...prev, loadingMessage];
+ });
+
+ await chatClient.streamChat(
+ {
+ message: message || '',
+ attachments:
+ currentAttachments.length > 0
+ ? currentAttachments
+ .filter((a) => a.file)
+ .map((a) => ({
+ id: `${Date.now()}_${Math.random()}`,
+ file: a.file as File,
+ name: a.name,
+ type: a.type,
+ size: a.size,
+ url: a.url || '',
+ metadata: {},
+ }))
+ : undefined,
+ agentId,
+ chatId,
+ modelId,
+ signal: abortRef.current.signal,
+ },
+ {
+ onContent: onStreamContent,
+ onMetaMessages: onMetaMessage,
+ onError: onStreamError,
+ onComplete: () => {
+ setIsStreaming(false);
+ setMessages((prev) => {
+ const last = prev[prev.length - 1];
+ if (last?.type === MESSAGE_TYPES.LOADING) {
+ return prev.slice(0, -1);
+ }
+ return prev;
+ });
+
+ // Auto-focus input after streaming completes
+ inputRef?.current?.focus();
+ },
+ },
+ );
+ } catch (error) {
+ console.error('Error in sendMessage:', error); // eslint-disable-line no-console
+ } finally {
+ setIsStreaming(false);
+ abortRef.current = null;
+ }
+ },
+ [
+ isStreaming,
+ chatClient,
+ agentId,
+ chatId,
+ modelId,
+ onStreamContent,
+ onMetaMessage,
+ onStreamError,
+ inputRef,
+ ],
+ );
+
+ const stopStreaming = useCallback((): void => {
+ if (abortRef.current) {
+ abortRef.current.abort();
+ }
+ setIsStreaming(false);
+
+ setMessages((prev) => {
+ const filtered = prev.filter((msg) => msg.type !== MESSAGE_TYPES.LOADING);
+
+ const updated = filtered.map((msg) => {
+ if (msg.metaMessages?.debugOn === true) {
+ return {
+ ...msg,
+ metaMessages: { ...msg.metaMessages, debugOn: false },
+ };
+ }
+ return msg;
+ });
+
+ const errorMessage: IMessage = {
+ id: Date.now() + Math.random(),
+ type: MESSAGE_TYPES.ERROR,
+ content: 'Generation interrupted by user',
+ updatedAt: Date.now(),
+ };
+
+ return [...updated, errorMessage];
+ });
+
+ // Auto-focus input after stopping stream
+ inputRef?.current?.focus();
+ }, [inputRef]);
+
+ const retryLastMessage = useCallback(() => {
+ const lastUserMessage = messages.filter((msg) => msg.type === MESSAGE_TYPES.USER).pop();
+
+ if (lastUserMessage) {
+ setMessages((prev) =>
+ prev.filter((msg) => msg.type !== MESSAGE_TYPES.ERROR && msg.id !== lastUserMessage.id),
+ );
+
+ const content = typeof lastUserMessage.content === 'string' ? lastUserMessage.content : '';
+ sendMessage(content, lastUserMessage.attachments || [], true);
+ }
+ }, [messages, sendMessage]);
+
+ return {
+ messages,
+ setMessages,
+ isStreaming,
+ setIsStreaming,
+ sendMessage,
+ stopStreaming,
+ retryLastMessage,
+ };
+};
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-file-upload.ts b/packages/app/src/react/features/ai-chat/hooks/use-file-upload.ts
new file mode 100644
index 00000000..3e255d2f
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/hooks/use-file-upload.ts
@@ -0,0 +1,278 @@
+import { ALLOWED_FILE_SIZE, MAX_UPLOADS } from '@react/features/ai-chat/constants';
+import type {
+ IFileAttachment,
+ IFileUpload,
+ IUploadStatus,
+} from '@react/features/ai-chat/types/chat';
+import {
+ generateUniqueFileId,
+ uploadFiles,
+ validateSingleFile,
+} from '@react/features/ai-chat/utils/file';
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+/**
+ * File upload hook options
+ */
+interface IFileUploadOptions {
+ agentId?: string;
+ chatId?: string;
+}
+
+/**
+ * Custom hook for managing file uploads with preview support
+ *
+ * @param options - Hook configuration with agentId and chatId
+ * @returns File upload state and methods
+ *
+ * @example
+ * ```typescript
+ * const {
+ * attachments,
+ * uploading,
+ * process,
+ * remove,
+ * clear,
+ * } = useFileUpload({ agentId: 'agent-123', chatId: 'chat-456' });
+ *
+ * // Process files from input
+ * await process(fileList);
+ *
+ * // Remove single file
+ * remove(0);
+ *
+ * // Clear all
+ * clear();
+ * ```
+ */
+export const useFileUpload = (options: IFileUploadOptions): IFileUpload => {
+ const { agentId, chatId } = options;
+
+ // State
+ const [attachments, setAttachments] = useState<IFileAttachment[]>([]);
+ const [status, setStatus] = useState<Record<string, IUploadStatus>>({});
+ const [uploading, setUploading] = useState(false);
+ const [errorMessage, setErrorMessage] = useState('');
+ const [toast, setToast] = useState('');
+ const [showToast, setShowToast] = useState(false);
+
+ // Refs
+ const blobsRef = useRef<Set<string>>(new Set());
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ // Auto-hide error message after 5 seconds
+ useEffect(() => {
+ let timer: ReturnType<typeof setTimeout>;
+ if (errorMessage) {
+ timer = setTimeout(() => setErrorMessage(''), 5000);
+ }
+ return () => {
+ if (timer) clearTimeout(timer);
+ };
+ }, [errorMessage]);
+
+ // Handle upload error
+ const onError = useCallback(
+ (fileName: string, message: string) => {
+ setErrorMessage(message);
+
+ const target = attachments.find((a) => a.name === fileName);
+
+ if (target?.blobUrl) {
+ URL.revokeObjectURL(target.blobUrl);
+ blobsRef.current.delete(target.blobUrl);
+ }
+
+ setAttachments(attachments.filter((a) => a.name !== fileName));
+
+ setStatus((prev) => {
+ const next = { ...prev };
+ delete next[fileName];
+ return next;
+ });
+
+ if (inputRef.current) inputRef.current.value = '';
+ },
+ [attachments],
+ );
+
+ // Process files for upload
+ const processFiles = useCallback(
+ async (files: File[]) => {
+ if (files.length === 0) return;
+
+ const slots = MAX_UPLOADS - attachments.length;
+
+ if (slots <= 0) {
+ setErrorMessage(`Maximum ${MAX_UPLOADS} files allowed`);
+ return;
+ }
+
+ const validated = files.map((file) => ({
+ file,
+ error: validateSingleFile(file),
+ id: generateUniqueFileId(file),
+ }));
+
+ const valid = validated.filter((item) => !item.error);
+ const invalid = validated.filter((item) => item.error);
+
+ if (invalid.length > 0) {
+ setErrorMessage(invalid[0].error || 'Failed to upload file');
+ }
+
+ if (valid.length > 0) {
+ const pending = valid.slice(0, slots);
+
+ // Create attachments with blob URLs for images
+ const created: IFileAttachment[] = pending.map(({ file, id }) => {
+ let blobUrl: string | null = null;
+ if (file.type.startsWith('image/')) {
+ try {
+ blobUrl = URL.createObjectURL(file);
+ blobsRef.current.add(blobUrl);
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.error('[FileUpload] Error creating blob URL:', err);
+ }
+ }
+ return { id, file, blobUrl, name: file.name, type: file.type, size: file.size };
+ });
+
+ setAttachments((prev) => [...prev, ...created]);
+
+ setStatus((prev) => {
+ const next = { ...prev };
+ pending.forEach(({ file }) => {
+ next[file.name] = { status: 'uploading', progress: 0 };
+ });
+ return next;
+ });
+
+ setUploading(true);
+
+ const uploads = created.map(async (attachment) => {
+ try {
+ const response = await uploadFiles({
+ files: [attachment.file],
+ agentId,
+ chatId,
+ });
+
+ const uploaded = response.files?.[0];
+
+ if (uploaded) {
+ setAttachments((prev) =>
+ prev.map((a) => (a.id === attachment.id ? { ...a, url: uploaded.url } : a)),
+ );
+ setStatus((prev) => ({
+ ...prev,
+ [attachment.name]: { status: 'completed', progress: 100 },
+ }));
+ }
+ } catch {
+ setStatus((prev) => ({
+ ...prev,
+ [attachment.name]: { status: 'error', progress: 0 },
+ }));
+ onError(
+ attachment.name,
+ attachment.size > ALLOWED_FILE_SIZE ? 'File size exceeds 5MB limit' : 'Upload failed',
+ );
+ }
+ });
+
+ await Promise.all(uploads);
+ setUploading(false);
+ }
+ },
+ [attachments.length, agentId, chatId, onError],
+ );
+
+ // Handle file input change
+ const onSelect = useCallback(
+ async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(e.target.files || []).slice(0, MAX_UPLOADS);
+ await processFiles(files);
+ },
+ [processFiles],
+ );
+
+ // Remove attachment by index
+ const remove = useCallback(
+ (index: number) => {
+ const target = attachments[index];
+
+ setAttachments((prev) => prev.filter((_, i) => i !== index));
+
+ setStatus((prev) => {
+ const next = { ...prev };
+ delete next[target.name];
+ return next;
+ });
+
+ if (inputRef.current) inputRef.current.value = '';
+ },
+ [attachments],
+ );
+
+ // Clear all attachments
+ const clear = useCallback(
+ (preserveBlobUrls = false) => {
+ if (preserveBlobUrls) {
+ attachments.forEach((a) => {
+ if (a.blobUrl) blobsRef.current.delete(a.blobUrl);
+ });
+ } else {
+ attachments.forEach((a) => {
+ if (a.blobUrl) {
+ URL.revokeObjectURL(a.blobUrl);
+ blobsRef.current.delete(a.blobUrl);
+ }
+ });
+ }
+
+ setAttachments([]);
+ setStatus({});
+ if (inputRef.current) inputRef.current.value = '';
+ },
+ [attachments],
+ );
+
+ // Cleanup unused blob URLs
+ const cleanup = useCallback(() => {
+ const active = new Set<string>();
+
+ attachments.forEach((a) => {
+ if (a.blobUrl) active.add(a.blobUrl);
+ });
+
+ const stale: string[] = [];
+ blobsRef.current.forEach((url) => {
+ if (!active.has(url)) {
+ URL.revokeObjectURL(url);
+ stale.push(url);
+ }
+ });
+
+ stale.forEach((url) => blobsRef.current.delete(url));
+ }, [attachments]);
+
+ return {
+ attachments,
+ status,
+ uploading,
+ toast,
+ showToast,
+ errorMessage,
+ inputRef,
+ onSelect,
+ process: processFiles,
+ remove,
+ clear,
+ cleanup,
+ setShowToast,
+ setToast,
+ setErrorMessage,
+ };
+};
diff --git a/packages/app/src/react/features/ai-chat/types/chat.ts b/packages/app/src/react/features/ai-chat/types/chat.ts
new file mode 100644
index 00000000..644be80e
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/chat.ts
@@ -0,0 +1,245 @@
+/* eslint-disable no-unused-vars */
+import type { ChangeEvent, Dispatch, RefObject, SetStateAction } from 'react';
+
+// ============================================================================
+// MESSAGE TYPES
+// ============================================================================
+
+export type TMessageType = 'user' | 'system' | 'debug' | 'error' | 'loading' | 'meta';
+
+export interface IFunctionCall {
+ name?: string;
+ topic?: string;
+ arguments?: Record<string, unknown>;
+}
+
+export interface IMetaMessages {
+ hashId?: string;
+ debugOn?: boolean;
+ debug?: string;
+ title?: string;
+ statusMessage?: string;
+ function?: string;
+ callParams?: unknown;
+ parameters?: unknown;
+ functionCall?: IFunctionCall;
+}
+
+export interface IAttachment {
+ name: string;
+ type: string;
+ size: number;
+ url?: string;
+ blobUrl?: string | null;
+ file?: File;
+}
+
+export interface IMessage {
+ id: number;
+ type: TMessageType;
+ content: string;
+ metaMessages?: IMetaMessages;
+ updatedAt?: number;
+ attachments?: IAttachment[];
+}
+
+// ============================================================================
+// FILE & ATTACHMENT TYPES
+// ============================================================================
+
+export interface IMessageFile {
+ id: string;
+ file: File;
+ url?: string;
+ name?: string;
+ type?: string;
+ size?: number;
+ metadata: {
+ key?: string;
+ fileType?: string;
+ publicUrl?: string;
+ previewUrl?: string;
+ isUploading?: boolean;
+ };
+}
+
+export interface IFileAttachment {
+ id: string;
+ file: File;
+ blobUrl: string | null;
+ name: string;
+ type: string;
+ size: number;
+ url?: string;
+}
+
+export interface IUploadStatus {
+ status: 'uploading' | 'completed' | 'error';
+ progress: number;
+}
+
+// ============================================================================
+// STREAMING & API TYPES
+// ============================================================================
+
+export interface IStreamChunk {
+ conversationTurnId?: string;
+ content?: string;
+ debugOn?: boolean;
+ title?: string;
+ debug?: string;
+ status_message?: string;
+ callParams?: string;
+ parameters?: Record<string, unknown>;
+ function?: string;
+ function_call?: IFunctionCall;
+ hashId?: string;
+ error?: string;
+ isError?: boolean;
+}
+
+export interface IStreamConfig {
+ agentId: string;
+ chatId: string;
+ domain?: string;
+ port?: number;
+ message: string;
+ modelId?: string;
+ attachments?: IMessageFile[];
+ enableMetaMessages?: boolean;
+ signal: AbortSignal;
+ headers?: Record<string, string>;
+}
+
+export interface IStreamCallbacks {
+ onContent: (content: string, turnId?: string) => void;
+ onMetaMessages?: (metaMessages: IMetaMessages, turnId?: string) => void;
+ onError: (error: IChatError) => void;
+ onStart?: () => void;
+ onComplete: () => void;
+}
+
+export type TErrorType = 'stream' | 'network' | 'abort' | 'system';
+
+export interface IChatError {
+ message: string;
+ type: TErrorType;
+ turnId?: string;
+ originalError?: Error | unknown;
+ isAborted?: boolean;
+}
+
+export interface IAPIConfig {
+ domain?: string;
+ port?: number;
+ baseUrl?: string;
+ defaultHeaders?: Record<string, string>;
+ timeout?: number;
+ retry?: { attempts: number; delay: number };
+}
+
+// ============================================================================
+// SCROLL TYPES
+// ============================================================================
+
+export type TScrollBehavior = 'smooth' | 'auto' | 'instant';
+export type TScrollLogicalPosition = 'start' | 'center' | 'end' | 'nearest';
+
+export interface IScrollOptions {
+ behavior?: TScrollBehavior;
+ force?: boolean;
+ delay?: number;
+}
+
+export interface IScrollToElementOptions {
+ behavior?: TScrollBehavior;
+ block?: TScrollLogicalPosition;
+ inline?: TScrollLogicalPosition;
+}
+
+export interface IScrollPosition {
+ scrollTop: number;
+ scrollHeight: number;
+ clientHeight: number;
+ distanceFromBottom: number;
+ isNearBottom: boolean;
+}
+
+// ============================================================================
+// DEBUG TYPES
+// ============================================================================
+
+export interface IDebugInfo {
+ content?: string | string[];
+ metaMessages?: IMetaMessages;
+ timestamp?: number;
+ updatedAt: number;
+}
+
+// ============================================================================
+// HOOK RETURN TYPES
+// ============================================================================
+
+/**
+ * Interface for focusable input elements
+ * Used for auto-focus functionality after stream completion
+ */
+export interface IFocusableInput {
+ focus: () => void;
+}
+
+export interface IConfigOptions {
+ agentId: string;
+ chatId: string;
+ modelId?: string;
+ enableMetaMessages?: boolean;
+
+ /** Optional ref to input element for auto-focus on stream complete */
+ inputRef?: RefObject<IFocusableInput | null>;
+}
+
+export interface IChatState {
+ messages: IMessage[];
+ setMessages: Dispatch<SetStateAction<IMessage[]>>;
+ isStreaming: boolean;
+ setIsStreaming: Dispatch<SetStateAction<boolean>>;
+ sendMessage: (
+ message: string,
+ currentAttachments?: IAttachment[],
+ shouldSetUserMessage?: boolean,
+ ) => Promise<void>;
+ stopStreaming: () => void;
+ retryLastMessage: () => void;
+}
+
+export interface IFileUpload {
+ attachments: IFileAttachment[];
+ status: Record<string, IUploadStatus>;
+ uploading: boolean;
+ toast: string;
+ showToast: boolean;
+ errorMessage: string;
+ inputRef: RefObject<HTMLInputElement | null>;
+ onSelect: (e: ChangeEvent<HTMLInputElement>) => Promise<void>;
+ process: (files: File[]) => Promise<void>;
+ remove: (index: number) => void;
+ clear: () => void;
+ cleanup: () => void;
+ setShowToast: (show: boolean) => void;
+ setToast: (message: string) => void;
+ setErrorMessage: (message: string) => void;
+}
+
+export interface IScroll {
+ toBottom: (smooth?: boolean) => void;
+ smartToBottom: (smooth?: boolean) => void;
+}
+
+export interface IDragOptions {
+ onDrop: (files: File[]) => void | Promise<void>;
+}
+
+export interface IDragState {
+ isDragging: boolean;
+ dropRef: RefObject<HTMLDivElement | null>;
+}