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 AI Chat Components and Utilities for Improved Type Safety and Clarity
Salman-Ahamed305e6a7379b5
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 a199fb08..f6cb1b61 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@@ -4,17 +4,15 @@*/import {+ IStreamCallbacks,TAPIConfig,TChatError,- TFileAttachment,- IStreamCallbacks,TStreamChunk,TStreamConfig,} from '@react/features/ai-chat/types';-import { performanceMonitor } from '@react/features/ai-chat/utils';+import { parseChunk, parseStreamChunks, performanceMonitor } from '@react/features/ai-chat/utils';import { CreateChatRequest } from '@react/shared/types/api-payload.types';import { CreateChatsResponse } from '@react/shared/types/api-results.types';-import { processStreamChunk, splitJSONStream } from '@src/react/features/ai-chat/utils/stream';/*** Default configuration for the Chat API Client@@ -213,7 +211,7 @@ export class ChatAPIClient {// Parse JSON chunksconst processingStart = performance.now();- const chunks = splitJSONStream(accumulatedData);+ const chunks = parseStreamChunks(accumulatedData);const processingTime = performance.now() - processingStart;// Record processing time if we parsed chunks@@ -244,7 +242,7 @@ export class ChatAPIClient {callbacks: Pick<IStreamCallbacks, 'onContent' | 'onMetaMessages'>,): Promise<void> {const { onContent, onMetaMessages } = callbacks;- const processed = processStreamChunk(chunk);+ const processed = parseChunk(chunk);// Extract conversation turn ID from chunkconst turnId = chunk.conversationTurnId;@@ -370,57 +368,4 @@ export class ChatAPIClient {return response.json() as Promise<CreateChatsResponse>;}-- /**- * Uploads a file for chat attachment- *- * @param file - File to upload- * @param agentId - Agent ID- * @param chatId - Optional conversation ID- * @returns File attachment metadata- *- * @example- * ```typescript- * const attachment = await client.uploadFile(file, 'agent-123');- * // Use attachment.url in chat message- * ```- */- async uploadFile(file: File, agentId: string, chatId?: string): Promise<TFileAttachment> {- const formData = new FormData();- formData.append('file', file);-- const headers: Record<string, string> = {- 'X-AGENT-ID': agentId,- ...(chatId ? { 'x-conversation-id': chatId } : {}),- };-- try {- const url = `${this.config.baseUrl}/upload`;- const response = await fetch(url, {- method: 'POST',- headers,- body: formData,- });-- if (!response.ok) throw new Error(`Upload failed: ${response.statusText}`);-- const data = await response.json();-- // Handle different response structures (same as utils/file.ts pattern)- const runtimeFile = data?.files?.[0];- const fileUrl = runtimeFile?.url || data?.file?.url || data.url || data.publicUrl;- const fileType = runtimeFile?.mimetype || data?.file?.type || file.type;-- return {- url: fileUrl || '',- name: file.name,- type: fileType,- size: file.size,- };- } catch (error) {- throw new Error(- `Failed to upload file: ${error instanceof Error ? error.message : 'Unknown error'}`,- );- }- }}diff --git a/packages/app/src/react/features/ai-chat/components/chat/chat.tsx b/packages/app/src/react/features/ai-chat/components/chat/chat.tsxindex 6d563cb8..be7e3e59 100644--- a/packages/app/src/react/features/ai-chat/components/chat/chat.tsx+++ b/packages/app/src/react/features/ai-chat/components/chat/chat.tsx@@ -15,7 +15,7 @@ export const Chat: FC<IProps> = memo((props) => {switch (type) {case MESSAGE_TYPES.USER:- return <User message={content} files={attachments} />;+ return <User message={content} attachments={attachments} />;case MESSAGE_TYPES.LOADING:return <Loading />;case MESSAGE_TYPES.META:diff --git a/packages/app/src/react/features/ai-chat/components/chat/message/meta.tsx b/packages/app/src/react/features/ai-chat/components/chat/message/meta.tsxindex b06e3702..5c06a796 100644--- a/packages/app/src/react/features/ai-chat/components/chat/message/meta.tsx+++ b/packages/app/src/react/features/ai-chat/components/chat/message/meta.tsx@@ -1,5 +1,5 @@import { TMetaMessage } from '@react/features/ai-chat/types';-import { createThinkingManager, formatStatusMessage } from '@react/features/ai-chat/utils';+import { createThinkingManager, formatStatus } from '@react/features/ai-chat/utils';import { FC, useEffect, useRef, useState } from 'react';type TProps = {@@ -21,7 +21,7 @@ export const Meta: FC<TProps> = ({ data, scrollToBottom }) => {const manager = thinkingManagerRef.current;if (metaMessages?.statusMessage) {- const formatted = formatStatusMessage(metaMessages.statusMessage);+ const formatted = formatStatus(metaMessages.statusMessage);setThinkingMessage(formatted);manager.stop();return;diff --git a/packages/app/src/react/features/ai-chat/components/chat/message/user.tsx b/packages/app/src/react/features/ai-chat/components/chat/message/user.tsxindex a71a7d4d..276a9beb 100644--- a/packages/app/src/react/features/ai-chat/components/chat/message/user.tsx+++ b/packages/app/src/react/features/ai-chat/components/chat/message/user.tsx@@ -4,20 +4,20 @@ import { FC } from 'react';type TProps = {message: string;- files?: TAttachment[];+ attachments?: TAttachment[];};-export const User: FC<TProps> = ({ message, files }) => {- const hasFiles = files && files.length > 0;+export const User: FC<TProps> = ({ message, attachments }) => {+ const hasAttachments = attachments && attachments.length > 0;const hasMessage = message.trim().length > 0;- if (!hasFiles && !hasMessage) return null;+ if (!hasAttachments && !hasMessage) return null;return (<div className="break-all flex flex-col items-end">- {hasFiles && (+ {hasAttachments && (<div className="flex flex-nowrap gap-2 mb-2 overflow-x-auto">- {files.map((attachment) => (+ {attachments.map((attachment) => (<FileItemPreviewkey={attachment.blobUrl || attachment.url || attachment.name}attachment={attachment}diff --git a/packages/app/src/react/features/ai-chat/components/footer/input.tsx b/packages/app/src/react/features/ai-chat/components/footer/input.tsxindex 3fac4936..b5af27c1 100644--- a/packages/app/src/react/features/ai-chat/components/footer/input.tsx+++ b/packages/app/src/react/features/ai-chat/components/footer/input.tsx@@ -4,9 +4,9 @@ import { AttachmentButton, FileItemPreview, SendButton } from '@react/features/aimport { useChatStores, useClipboardPaste } from '@react/features/ai-chat/hooks';import {adjustTextareaHeight,- createFileFromText,forceScrollToBottomImmediate,scrollManager,+ textToFile,} from '@react/features/ai-chat/utils';import { MAX_CHAT_MESSAGE_LENGTH } from '@react/shared/constants';import { cn } from '@react/shared/utils/general';@@ -96,7 +96,7 @@ export const ChatInput = () => {onFilePaste: addFiles,targetRef: inputRef,largeTextThreshold: LARGE_TEXT_THRESHOLD,- onLargeTextPaste: (text) => addFiles([createFileFromText(text).file]),+ onLargeTextPaste: (text) => addFiles([textToFile(text).file]),});const isMaxLengthReached = message.length === maxLength;diff --git a/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsx b/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsxindex ceb651be..131c61ce 100644--- a/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsx+++ b/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsx@@ -85,6 +85,7 @@ export const ChatContextProvider: FC<TChildren> = ({ children }) => {try {const attachments = fileUpload.attachments.map((f) => ({+ id: f.id,name: f.name,type: f.type,size: f.size,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.tsindex e4ac3f48..82f44a9c 100644--- 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@@ -1,14 +1,6 @@import { ALLOWED_FILE_SIZE, MAX_UPLOADS } from '@react/features/ai-chat/constants';-import type {- TFileAttachment,- IFileUpload,- TUploadStatus,-} from '@react/features/ai-chat/types';-import {- generateUniqueFileId,- uploadFiles,- validateSingleFile,-} from '@react/features/ai-chat/utils';+import type { IFileUpload, TAttachment, TUploadStatus } from '@react/features/ai-chat/types';+import { createFileId, uploadFiles, validateFile } from '@react/features/ai-chat/utils';import { useCallback, useEffect, useRef, useState } from 'react';type TFileUploadConfig = {@@ -19,7 +11,7 @@ type TFileUploadConfig = {export const useFileUpload = (options: TFileUploadConfig): IFileUpload => {const { agentId, chatId } = options;- const [attachments, setAttachments] = useState<TFileAttachment[]>([]);+ const [attachments, setAttachments] = useState<TAttachment[]>([]);const [status, setStatus] = useState<Record<string, TUploadStatus>>({});const [uploading, setUploading] = useState(false);const [errorMessage, setErrorMessage] = useState('');@@ -71,8 +63,8 @@ export const useFileUpload = (options: TFileUploadConfig): IFileUpload => {const validated = files.map((file) => ({file,- error: validateSingleFile(file),- id: generateUniqueFileId(file),+ error: validateFile(file),+ id: createFileId(file),}));const valid = validated.filter((item) => !item.error);@@ -85,7 +77,7 @@ export const useFileUpload = (options: TFileUploadConfig): IFileUpload => {if (valid.length > 0) {const pending = valid.slice(0, slots);- const created: TFileAttachment[] = pending.map(({ file, id }) => {+ const created: TAttachment[] = pending.map(({ file, id }) => {let blobUrl: string | null = null;if (file.type.startsWith('image/')) {try {diff --git a/packages/app/src/react/features/ai-chat/types/file.ts b/packages/app/src/react/features/ai-chat/types/file.tsindex ea1193ca..e0a305d7 100644--- a/packages/app/src/react/features/ai-chat/types/file.ts+++ b/packages/app/src/react/features/ai-chat/types/file.ts@@ -14,16 +14,6 @@ export type TUploadFile = {};};-export type TFileAttachment = {- id: string;- file: File;- blobUrl: string | null;- name: string;- type: string;- size: number;- url?: string;-};-export type TUploadStatus = {status: 'uploading' | 'completed' | 'error';progress: number;diff --git a/packages/app/src/react/features/ai-chat/types/hooks.ts b/packages/app/src/react/features/ai-chat/types/hooks.tsindex 62474b68..32d59e62 100644--- a/packages/app/src/react/features/ai-chat/types/hooks.ts+++ b/packages/app/src/react/features/ai-chat/types/hooks.ts@@ -1,6 +1,6 @@/* eslint-disable no-unused-vars */import type { Dispatch, RefObject, SetStateAction } from 'react';-import type { TAttachment, TChatMessage, TFileAttachment, TUploadStatus } from '.';+import type { TAttachment, TChatMessage, TUploadStatus } from '.';export type TFocusable = { focus: () => void };@@ -26,7 +26,7 @@ export interface IChatState {}export interface IFileUpload {- attachments: TFileAttachment[];+ attachments: TAttachment[];status: Record<string, TUploadStatus>;uploading: boolean;errorMessage: string;diff --git a/packages/app/src/react/features/ai-chat/types/message.ts b/packages/app/src/react/features/ai-chat/types/message.tsindex f47ae2c0..c668bccb 100644--- a/packages/app/src/react/features/ai-chat/types/message.ts+++ b/packages/app/src/react/features/ai-chat/types/message.ts@@ -21,6 +21,7 @@ export type TMetaMessage = {};export type TAttachment = {+ id: string;name: string;type: string;size: number;diff --git a/packages/app/src/react/features/ai-chat/utils/file.ts b/packages/app/src/react/features/ai-chat/utils/file.tsindex ac949463..47223719 100644--- a/packages/app/src/react/features/ai-chat/utils/file.ts+++ b/packages/app/src/react/features/ai-chat/utils/file.ts@@ -1,21 +1,12 @@import { ALLOWED_FILE_SIZE, MAX_UPLOADS } from '@react/features/ai-chat/constants';import type { TUploadFile } from '@react/features/ai-chat/types';-/**- * File upload limits configuration- */export const FILE_LIMITS = {MAX_ATTACHED_FILES: MAX_UPLOADS,MAX_FILE_SIZE: ALLOWED_FILE_SIZE,} as const;-/**- * Creates a TUploadFile from plain text content- * Useful for converting pasted text into a file attachment- * @param content - The text content to convert to a file- * @returns TUploadFile object with the text content as a .txt file- */-export const createFileFromText = (content: string): TUploadFile => {+export const textToFile = (content: string): TUploadFile => {const timestamp = new Date().toISOString().replace(/[:.]/g, '-');const name = `text-${timestamp}.txt`;const blob = new Blob([content], { type: 'text/plain' });@@ -25,50 +16,24 @@ export const createFileFromText = (content: string): TUploadFile => {return { file, metadata: { fileType: 'text/plain', isUploading: false }, id };};-/**- * Validates a single file for upload- * @param file - File to validate- * @returns Error message string if invalid, undefined if valid- */-export const validateSingleFile = (file: File): string | undefined => {+export const validateFile = (file: File): string | undefined => {if (file.size > ALLOWED_FILE_SIZE) {return `File "${file.name}" exceeds 5MB size limit`;}return undefined;};-/**- * Generates a unique ID for a file based on name and timestamp- * @param file - File to generate ID for- * @returns Unique file ID string- */-export const generateUniqueFileId = (file: File): string => {+export const createFileId = (file: File): string => {const timestamp = Date.now();const randomSuffix = Math.random().toString(36).substring(2, 8);return `${file.name}-${timestamp}-${randomSuffix}`;};-type TUploadFilesParams = {- files: File[];- agentId?: string;- chatId?: string;-};--type TUploadFilesResponse = {- files?: Array<{- url: string;- name?: string;- mimetype?: string;- }>;-};+type TUploadConfig = { files: File[]; agentId?: string; chatId?: string };+type TUploadResult = { files?: Array<{ url: string; name?: string; mimetype?: string }> };-/**- * Uploads files to the chat API- * @param params - Upload parameters including files, agentId, and chatId- * @returns Promise with uploaded file information- */-export const uploadFiles = async (params: TUploadFilesParams): Promise<TUploadFilesResponse> => {- const { files, agentId, chatId } = params;+export const uploadFiles = async (config: TUploadConfig): Promise<TUploadResult> => {+ const { files, agentId, chatId } = config;const formData = new FormData();files.forEach((file) => {@@ -76,12 +41,8 @@ export const uploadFiles = async (params: TUploadFilesParams): Promise<TUploadFi});const headers: Record<string, string> = {};- if (agentId) {- headers['X-AGENT-ID'] = agentId;- }- if (chatId) {- headers['x-conversation-id'] = chatId;- }+ if (agentId) headers['X-AGENT-ID'] = agentId;+ if (chatId) headers['x-conversation-id'] = chatId;const response = await fetch('/api/page/chat/upload', {method: 'POST',@@ -93,5 +54,5 @@ export const uploadFiles = async (params: TUploadFilesParams): Promise<TUploadFithrow new Error(`Upload failed: ${response.statusText}`);}- return response.json() as Promise<TUploadFilesResponse>;+ return response.json() as Promise<TUploadResult>;};diff --git a/packages/app/src/react/features/ai-chat/utils/model.ts b/packages/app/src/react/features/ai-chat/utils/model.tsindex b077d84a..ed93578d 100644--- a/packages/app/src/react/features/ai-chat/utils/model.ts+++ b/packages/app/src/react/features/ai-chat/utils/model.ts@@ -1,6 +1,3 @@-/**- * Badge configuration for model tags (enterprise, smythos, personal, limited)- */const BADGE_TAGS: Record<string, boolean> = {enterprise: true,smythos: true,@@ -8,11 +5,6 @@ const BADGE_TAGS: Record<string, boolean> = {limited: true,};-/**- * Extracts display badge from model tags- * @param tags - Array of model tags- * @returns Badge string for display- */export const getBadgeFromTags = (tags: string[]): string => {return tags.filter((tag) => BADGE_TAGS[tag?.toLowerCase()]).join(' ');};diff --git a/packages/app/src/react/features/ai-chat/utils/stream.ts b/packages/app/src/react/features/ai-chat/utils/stream.tsindex 85ed0485..0e2b2129 100644--- a/packages/app/src/react/features/ai-chat/utils/stream.ts+++ b/packages/app/src/react/features/ai-chat/utils/stream.ts@@ -1,11 +1,6 @@/* eslint-disable no-unused-vars */-/**- * Stream processing utilities for chat responses- */-import { TStreamChunk, TThinkingType } from '@react/features/ai-chat/types';-/** Function-specific thinking messages that cycle during function execution */const FUNCTION_THINKING_MESSAGES = ['Using skill: {functionName}','Still working on {functionName}',@@ -15,7 +10,6 @@ const FUNCTION_THINKING_MESSAGES = ['This is taking longer than usual. You can try waiting, or refresh the page.',];-/** General thinking messages that cycle during processing */const GENERAL_THINKING_MESSAGES = ['Thinking','Still thinking',@@ -25,12 +19,7 @@ const GENERAL_THINKING_MESSAGES = ['This is taking longer than usual. You can try waiting, or refresh the page.',];-/**- * Splits concatenated JSON objects from stream- * @param data - Raw string data from stream- * @returns Array of parsed JSON objects- */-export const splitJSONStream = (data: string): TStreamChunk[] => {+export const parseStreamChunks = (data: string): TStreamChunk[] => {if (!data || typeof data !== 'string') return [];const cleanData = data.trim();@@ -72,12 +61,7 @@ export const splitJSONStream = (data: string): TStreamChunk[] => {return parsedChunks;};-/**- * Formats function name from snake_case to Title Case- * @param functionName - Raw function name- * @returns Formatted function name- */-export const formatFunctionName = (functionName: string): string => {+export const toTitleCase = (functionName: string): string => {if (!functionName) return '';return functionName@@ -86,12 +70,7 @@ export const formatFunctionName = (functionName: string): string => {.join(' ');};-/**- * Formats status message with proper function names and durations- * @param statusMessage - Raw status message with placeholders- * @returns Formatted status message- */-export const formatStatusMessage = (statusMessage: string): string => {+export const formatStatus = (statusMessage: string): string => {if (!statusMessage) return '';let formatted = statusMessage;@@ -101,7 +80,7 @@ export const formatStatusMessage = (statusMessage: string): string => {if (/^\d+\s*(ms|s|sec|seconds?|minutes?|mins?|hours?|hrs?)$/i.test(functionName)) {return functionName;}- return formatFunctionName(functionName);+ return toTitleCase(functionName);});const durationPattern =@@ -118,17 +97,13 @@ export const formatStatusMessage = (statusMessage: string): string => {return formatted;};-/**- * Manages cycling through thinking messages with priority system- */-class ThinkingMessageManager {+class ThinkingManager {private currentType: TThinkingType | null = null;private currentIndex: number = 0;private intervalId: NodeJS.Timeout | null = null;private toolName: string = '';private callback: (message: string) => void;- /** Starts thinking messages with optional tool name */start(callback: (message: string) => void, toolName?: string): void {this.stop();@@ -137,7 +112,7 @@ class ThinkingMessageManager {this.currentIndex = 0;if (this.currentType === 'tools' && toolName) {- this.toolName = formatFunctionName(toolName);+ this.toolName = toTitleCase(toolName);}const initialMessage = this.getCurrentMessage();@@ -151,7 +126,6 @@ class ThinkingMessageManager {}, intervalTime);}- /** Stops thinking messages and clears state */stop(): void {if (this.intervalId) {clearInterval(this.intervalId);@@ -186,15 +160,9 @@ class ThinkingMessageManager {}}-/** Creates a new ThinkingMessageManager instance */-export const createThinkingManager = (): ThinkingMessageManager => new ThinkingMessageManager();+export const createThinkingManager = (): ThinkingManager => new ThinkingManager();-/**- * Processes a stream chunk and extracts relevant information- * @param chunk - Stream chunk to process- * @returns Processed chunk data- */-export const processStreamChunk = (chunk: TStreamChunk) => {+export const parseChunk = (chunk: TStreamChunk) => {const errorMessage = chunk.error || (chunk.isError ? chunk.content : null);return {diff --git a/packages/app/src/react/features/ai-chat/utils/textarea.ts b/packages/app/src/react/features/ai-chat/utils/textarea.tsindex 0f6a39e4..7687fbca 100644--- a/packages/app/src/react/features/ai-chat/utils/textarea.ts+++ b/packages/app/src/react/features/ai-chat/utils/textarea.ts@@ -1,13 +1,5 @@-/**- * Default max height for textarea auto-resize (in pixels)- */const DEFAULT_TEXTAREA_MAX_HEIGHT = 160;-/**- * Adjusts textarea height based on its content- * @param textarea - The textarea element to adjust- * @param maxHeight - Maximum height in pixels (defaults to 160)- */export const adjustTextareaHeight = (textarea: HTMLTextAreaElement | null,maxHeight: number = DEFAULT_TEXTAREA_MAX_HEIGHT,@@ -19,4 +11,3 @@ export const adjustTextareaHeight = (textarea.style.height = `${newHeight}px`;textarea.style.overflowY = newHeight === maxHeight ? 'auto' : 'hidden';};-