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 AI Chat Utilities and Update Imports for Streamlined Codebase

Salman-Ahamed1589dcbdb4d1
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 8c2fff03..c7fd79ad 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
@@ -12,9 +12,9 @@ import {
IStreamConfig,
} from '@react/features/ai-chat/types/chat.types';
import { performanceMonitor } from '@react/features/ai-chat/utils/chat-performance-monitor';
-import { processStreamChunk, splitJSONStream } from '@react/features/ai-chat/utils/stream.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
diff --git a/packages/app/src/react/features/ai-chat/components/chat/thinking-message.tsx b/packages/app/src/react/features/ai-chat/components/chat/thinking-message.tsx
index 4c44b219..21033e85 100644
--- a/packages/app/src/react/features/ai-chat/components/chat/thinking-message.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chat/thinking-message.tsx
@@ -1,7 +1,7 @@
import {
createThinkingManager,
formatStatusMessage,
-} from '@react/features/ai-chat/utils/stream.utils';
+} from '@src/react/features/ai-chat/utils/stream';
import { FC, useEffect, useRef, useState } from 'react';
import { IMetaMessages } from '../../types/chat';
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.tsx
index 7d74eb13..dccf357a 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,13 +4,13 @@ import '../../styles/index.css';
import { AttachmentButton, SendButton } from '@react/features/ai-chat/components';
import { useChatStores, useClipboardPaste } from '@react/features/ai-chat/hooks';
import { adjustTextareaHeight, createFileFromText } from '@react/features/ai-chat/utils';
-import {
- forceScrollToBottomImmediate,
- scrollManager,
-} from '@react/features/ai-chat/utils/scroll-utils';
import { MAX_CHAT_MESSAGE_LENGTH } from '@react/shared/constants';
import { cn } from '@react/shared/utils/general';
import { FileItemPreview } from '@src/react/features/ai-chat/components/common/FileItemPreview';
+import {
+ forceScrollToBottomImmediate,
+ scrollManager,
+} from '@src/react/features/ai-chat/utils/scroll';
const LARGE_TEXT_THRESHOLD = 4000;
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-scroll.ts b/packages/app/src/react/features/ai-chat/hooks/use-scroll.ts
index d5d28442..e8f3aa7d 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-scroll.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-scroll.ts
@@ -1,6 +1,6 @@
import { RefObject, useCallback, useEffect, useState } from 'react';
-import { scrollManager } from '@react/features/ai-chat/utils/scroll-utils';
+import { scrollManager } from '@src/react/features/ai-chat/utils/scroll';
export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {
const [showScrollButton, setShowScrollButton] = useState(false);
diff --git a/packages/app/src/react/features/ai-chat/utils/file.ts b/packages/app/src/react/features/ai-chat/utils/file.ts
index 86a38d7b..46699ebe 100644
--- a/packages/app/src/react/features/ai-chat/utils/file.ts
+++ b/packages/app/src/react/features/ai-chat/utils/file.ts
@@ -1,5 +1,3 @@
-import { IMessageFile } from '@react/features/ai-chat/types/chat.types';
-
/**
* Constants for file upload limitations
*/
@@ -9,18 +7,9 @@ export const FILE_LIMITS = {
ACCEPTED_TYPES: ['*/*'], // Accept all file types like chatbot
} as const;
-/**
- * Gets local preview URL for a file if possible
- * @param {File} file - File to get preview for
- * @returns {string | null} Preview URL or null if preview not possible
- */
-export const getLocalPreviewUrl = (file: File): string | null => {
- return file.type.startsWith('image/') ? URL.createObjectURL(file) : null;
-};
-
/**
* Validates a single file against size constraints only
- * @param file The file to validate
+ * @param file - The file to validate
* @returns An error message if validation fails, null if validation passes
*/
export const validateSingleFile = (file: File): string | null => {
@@ -28,41 +17,17 @@ export const validateSingleFile = (file: File): string | null => {
return 'File size exceeds 5MB limit';
}
- // Accept all file types - no file type validation needed
- // Since we're accepting */* all file types are allowed
-
return null;
};
/**
- * Deletes a file from the server
- * @param key The file key to delete
+ * Generates a unique ID for a file
+ * @param file - The file to generate ID for
+ * @returns Unique file identifier string
*/
-export const deleteFile = async (key: string): Promise<boolean> => {
- try {
- const response = await fetch(`/api/page/chat/deleteFile?key=${encodeURIComponent(key)}`, {
- method: 'DELETE',
- });
- return response.ok;
- } catch {
- return false;
- }
-};
-
-// Helper function to generate a unique ID for each file
export const generateUniqueFileId = (file: File): string => {
return `${file.name}-${file.size}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
};
-/**
- * Creates file metadata object from a file
- * @param file The file to create metadata for
- * @returns FileWithMetadata object
- */
-export const createFileMetadata = (file: File): IMessageFile => ({
- file,
- id: generateUniqueFileId(file),
- metadata: { fileType: file.type, previewUrl: getLocalPreviewUrl(file), isUploading: true },
-});
/**
* Interface for upload files props
@@ -88,19 +53,8 @@ interface IUploadResponse {
/**
* Uploads files to the server
- *
* @param props - Upload configuration
* @returns Promise with upload response containing file URLs
- *
- * @example
- * ```typescript
- * const response = await uploadFiles({
- * files: [file1, file2],
- * agentId: 'agent-123',
- * chatId: 'chat-456',
- * });
- * console.log(response.files[0].url);
- * ```
*/
export const uploadFiles = async (props: IUploadFilesProps): Promise<IUploadResponse> => {
const { files, agentId, chatId } = props;
@@ -113,7 +67,6 @@ export const uploadFiles = async (props: IUploadFilesProps): Promise<IUploadResp
const headers: Record<string, string> = {};
- // Add agent and chat IDs if provided
if (agentId) {
headers['X-AGENT-ID'] = agentId;
}
@@ -132,13 +85,18 @@ export const uploadFiles = async (props: IUploadFilesProps): Promise<IUploadResp
}
const data = await response.json();
-
- // Normalize response structure
const runtimeFiles = data?.files || (data?.file ? [data.file] : []);
return {
files: runtimeFiles.map(
- (f: { url?: string; publicUrl?: string; mimetype?: string; type?: string; name?: string; size?: number }) => ({
+ (f: {
+ url?: string;
+ publicUrl?: string;
+ mimetype?: string;
+ type?: string;
+ name?: string;
+ size?: number;
+ }) => ({
url: f.url || f.publicUrl || '',
name: f.name,
type: f.mimetype || f.type,
@@ -150,4 +108,4 @@ export const uploadFiles = async (props: IUploadFilesProps): Promise<IUploadResp
console.error('Error uploading files:', error); // eslint-disable-line no-console
throw error;
}
-};
\ No newline at end of file
+};
diff --git a/packages/app/src/react/features/ai-chat/utils/scroll-utils.ts b/packages/app/src/react/features/ai-chat/utils/scroll.ts
similarity index 59%
rename from packages/app/src/react/features/ai-chat/utils/scroll-utils.ts
rename to packages/app/src/react/features/ai-chat/utils/scroll.ts
index fb858cf4..75cf9026 100644
--- a/packages/app/src/react/features/ai-chat/utils/scroll-utils.ts
+++ b/packages/app/src/react/features/ai-chat/utils/scroll.ts
@@ -1,5 +1,5 @@
/**
- * Professional scroll utilities for chat interface
+ * Scroll utilities for chat interface
* Provides smooth, performant, and reliable scrolling behavior
*/
@@ -15,15 +15,15 @@ interface ScrollToBottomOptions extends ScrollOptions {
}
/**
- * Professional scroll-to-bottom utility with multiple strategies
+ * Scroll-to-bottom utility with multiple strategies
*/
export class ScrollManager {
private static instance: ScrollManager;
private scrollContainer: HTMLElement | null = null;
- private isScrolling = false;
private scrollTimeout: number | null = null;
private lastForceScrollTime = 0;
+ /** Returns singleton instance of ScrollManager */
static getInstance(): ScrollManager {
if (!ScrollManager.instance) {
ScrollManager.instance = new ScrollManager();
@@ -31,23 +31,17 @@ export class ScrollManager {
return ScrollManager.instance;
}
- /**
- * Initialize scroll manager with container element
- */
+ /** Initialize scroll manager with container element */
init(container: HTMLElement | null): void {
this.scrollContainer = container;
}
- /**
- * Get the current scroll container
- */
+ /** Get the current scroll container */
getContainer(): HTMLElement | null {
return this.scrollContainer || this.findScrollContainer();
}
- /**
- * Find scroll container automatically
- */
+ /** Find scroll container automatically */
private findScrollContainer(): HTMLElement | null {
const selectors = [
'.overflow-auto',
@@ -66,41 +60,32 @@ export class ScrollManager {
/**
* Check if user is near bottom of scroll container
- *
- * ULTRA-AGGRESSIVE: Very forgiving threshold for smooth streaming
- * - 200px threshold (was 150px) - more aggressive auto-scroll
- * - Math.ceil for more lenient calculation
- * - Better for long chats and rapid content growth
+ * Uses 200px threshold for aggressive auto-scroll during streaming
*/
isNearBottom(threshold: number = 200): boolean {
const container = this.getContainer();
if (!container) return true;
const { scrollTop, scrollHeight, clientHeight } = container;
- // Use Math.ceil for more lenient behavior (rounds up distance)
const distanceFromBottom = Math.ceil(scrollHeight - scrollTop - clientHeight);
return distanceFromBottom <= threshold;
}
- /**
- * Professional scroll to bottom with multiple strategies
- */
+ /** Scroll to bottom with configurable options */
scrollToBottom(options: ScrollToBottomOptions = {}): Promise<void> {
return new Promise((resolve) => {
const { behavior = 'smooth', force = false, delay = 0 } = options;
- // Prevent too frequent force scrolls (reduced cooldown for better UX)
+ // Prevent too frequent force scrolls (100ms cooldown)
if (force) {
const now = Date.now();
if (now - this.lastForceScrollTime < 100) {
- // 100ms cooldown (reduced from 500ms)
resolve();
return;
}
this.lastForceScrollTime = now;
}
- // Clear any existing scroll timeout
if (this.scrollTimeout) {
clearTimeout(this.scrollTimeout);
}
@@ -113,44 +98,22 @@ export class ScrollManager {
return;
}
- /**
- * ULTRA-AGGRESSIVE SCROLL: Maximum responsiveness
- *
- * - force=true: Always scroll (no questions asked)
- * - force=false: Very lenient 200px threshold
- * - Result: User rarely loses scroll tracking
- *
- * Philosophy: During streaming, keeping content visible is
- * more important than respecting small scroll-up movements
- */
+ // Skip if not near bottom and not forced
if (!force && !this.isNearBottom(200)) {
- // Ultra-forgiving 200px threshold
resolve();
return;
}
- this.isScrolling = true;
-
- /**
- * PERFORMANCE: Direct scrollTo for instant response
- * - No animation delay
- * - Maximum responsiveness
- * - Perfect for streaming
- */
container.scrollTo({
top: container.scrollHeight,
behavior: behavior === 'instant' ? 'auto' : behavior,
});
- // Reset scrolling flag
if (behavior === 'smooth') {
this.scrollTimeout = window.setTimeout(() => {
- this.isScrolling = false;
resolve();
}, 300);
} else {
- // Instant scroll - no delay needed
- this.isScrolling = false;
resolve();
}
};
@@ -158,54 +121,40 @@ export class ScrollManager {
if (delay > 0) {
this.scrollTimeout = window.setTimeout(performScroll, delay);
} else {
- // Use requestAnimationFrame for better performance
requestAnimationFrame(performScroll);
}
});
}
- /**
- * Force scroll to bottom bypassing cooldown (for user-initiated scrolls)
- */
+ /** Force scroll to bottom bypassing cooldown (for user-initiated scrolls) */
forceScrollToBottomImmediate(options: ScrollToBottomOptions = {}): Promise<void> {
const originalCooldown = this.lastForceScrollTime;
- this.lastForceScrollTime = 0; // Reset cooldown
+ this.lastForceScrollTime = 0;
- // Explicitly set force to true and ensure it's not overridden
const forceOptions: ScrollToBottomOptions = {
...options,
force: true,
};
return this.scrollToBottom(forceOptions).finally(() => {
- this.lastForceScrollTime = originalCooldown; // Restore original cooldown
+ this.lastForceScrollTime = originalCooldown;
});
}
- /**
- * Smart scroll that respects user's scroll position
- */
+ /** Smart scroll that respects user's scroll position */
smartScrollToBottom(options: ScrollToBottomOptions = {}): Promise<void> {
return this.scrollToBottom({ ...options, force: false });
}
- /**
- * Reset force scroll cooldown (useful for user-initiated scrolls)
- */
+ /** Reset force scroll cooldown (useful for user-initiated scrolls) */
resetForceScrollCooldown(): void {
this.lastForceScrollTime = 0;
}
}
-// Export singleton instance
+// Singleton instance export
export const scrollManager = ScrollManager.getInstance();
-// Convenience functions
-export const scrollToBottom = (options?: ScrollToBottomOptions) =>
- scrollManager.scrollToBottom(options);
-
+// Convenience function for force scroll
export const forceScrollToBottomImmediate = (options?: ScrollToBottomOptions) =>
scrollManager.forceScrollToBottomImmediate(options);
-
-export const smartScrollToBottom = (options?: ScrollToBottomOptions) =>
- scrollManager.smartScrollToBottom(options);
diff --git a/packages/app/src/react/features/ai-chat/utils/stream.utils.ts b/packages/app/src/react/features/ai-chat/utils/stream.ts
similarity index 68%
rename from packages/app/src/react/features/ai-chat/utils/stream.utils.ts
rename to packages/app/src/react/features/ai-chat/utils/stream.ts
index defbeff3..14447674 100644
--- a/packages/app/src/react/features/ai-chat/utils/stream.utils.ts
+++ b/packages/app/src/react/features/ai-chat/utils/stream.ts
@@ -1,15 +1,11 @@
/* eslint-disable no-unused-vars */
/**
* Stream processing utilities for chat responses
- * Handles JSON parsing, message formatting, and status updates
- * Updated: callback signatures now include TThinkingType parameter
*/
import { IStreamChunk, TThinkingType } from '@react/features/ai-chat/types/chat.types';
-/**
- * Function-specific thinking messages that cycle during function execution
- */
+/** Function-specific thinking messages that cycle during function execution */
const FUNCTION_THINKING_MESSAGES = [
'Using skill: {functionName}',
'Still working on {functionName}',
@@ -19,9 +15,7 @@ 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
- */
+/** General thinking messages that cycle during processing */
const GENERAL_THINKING_MESSAGES = [
'Thinking',
'Still thinking',
@@ -33,40 +27,26 @@ const GENERAL_THINKING_MESSAGES = [
/**
* Splits concatenated JSON objects from stream
- * Handles edge cases like incomplete JSON, malformed chunks
- *
* @param data - Raw string data from stream
* @returns Array of parsed JSON objects
- *
- * @example
- * ```typescript
- * const data = '{"content":"Hello"}{"content":" World"}';
- * const chunks = splitJSONStream(data);
- * // Returns: [{ content: 'Hello' }, { content: ' World' }]
- * ```
*/
export const splitJSONStream = (data: string): IStreamChunk[] => {
- // Handle empty or invalid data
if (!data || typeof data !== 'string') return [];
const cleanData = data.trim();
if (!cleanData) return [];
- // Split by '}{' pattern - common in streaming JSON
const jsonStrings = cleanData
.split('}{')
.map((str, index, array) => {
let cleanStr = str.trim();
- // Skip empty strings
if (!cleanStr) return null;
- // Add opening brace if not first element
if (index !== 0 && !cleanStr.startsWith('{')) {
cleanStr = '{' + cleanStr;
}
- // Add closing brace if not last element
if (index !== array.length - 1 && !cleanStr.endsWith('}')) {
cleanStr += '}';
}
@@ -75,18 +55,15 @@ export const splitJSONStream = (data: string): IStreamChunk[] => {
})
.filter(Boolean) as string[];
- // Parse each JSON string
const parsedChunks = jsonStrings
.map((str) => {
try {
- // Validate before parsing
if (!str || str.length < 2 || !str.startsWith('{') || !str.endsWith('}')) {
return null;
}
return JSON.parse(str) as IStreamChunk;
} catch {
- // Silently skip invalid JSON
return null;
}
})
@@ -96,24 +73,13 @@ export const splitJSONStream = (data: string): IStreamChunk[] => {
};
/**
- * Formats function name from snake_case to Title Case for display
- *
+ * Formats function name from snake_case to Title Case
* @param functionName - Raw function name
* @returns Formatted function name
- *
- * @example
- * ```typescript
- * formatFunctionName('get_user_data');
- * // Returns: 'Get User Data'
- *
- * formatFunctionName('processPayment');
- * // Returns: 'Processpayment'
- * ```
*/
export const formatFunctionName = (functionName: string): string => {
if (!functionName) return '';
- // Convert snake_case to Title Case
return functionName
.split('_')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
@@ -122,46 +88,30 @@ export const formatFunctionName = (functionName: string): string => {
/**
* Formats status message with proper function names and durations
- * Replaces placeholders in curly braces with formatted values
- *
* @param statusMessage - Raw status message with placeholders
* @returns Formatted status message
- *
- * @example
- * ```typescript
- * formatStatusMessage('Calling {get_user_data} took {250} ms');
- * // Returns: 'Calling Get User Data took 250 ms'
- * ```
*/
export const formatStatusMessage = (statusMessage: string): string => {
if (!statusMessage) return '';
let formatted = statusMessage;
- // Pattern to match function names in curly braces: {function_name} or {functionName}
const functionPattern = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
formatted = formatted.replace(functionPattern, (match, functionName) => {
- // Check if this looks like a duration (contains numbers and time units)
if (/^\d+\s*(ms|s|sec|seconds?|minutes?|mins?|hours?|hrs?)$/i.test(functionName)) {
- // This is actually a duration, not a function name
return functionName;
}
- // Format as function name
return formatFunctionName(functionName);
});
- // Pattern to match durations in curly braces: {50 ms}, {2 seconds}, etc.
const durationPattern =
/\{(\d+(?:\.\d+)?\s*(?:ms|s|sec|seconds?|minutes?|mins?|hours?|hrs?))\}/gi;
formatted = formatted.replace(durationPattern, (_match, duration) => {
- // Clean up the duration formatting
return duration.trim();
});
- // Pattern to match pure numbers in curly braces that might be durations: {50}
const numberPattern = /\{(\d+(?:\.\d+)?)\}/g;
formatted = formatted.replace(numberPattern, (_match, number) => {
- // Assume it's milliseconds if it's just a number
return `${number} ms`;
});
@@ -169,7 +119,6 @@ export const formatStatusMessage = (statusMessage: string): string => {
};
/**
- * Unified thinking message manager
* Manages cycling through thinking messages with priority system
*/
class ThinkingMessageManager {
@@ -179,17 +128,8 @@ class ThinkingMessageManager {
private toolName: string = '';
private callback: (message: string) => void;
- /**
- * Starts thinking messages with priority system
- * Priority: status (3) > function (2) > general (1)
- *
- * @param type - Type of thinking message
- * @param callback - Callback to invoke with updated messages
- * @param toolName - Function name for function type
- * @param statusMessage - Status message for status type
- */
+ /** Starts thinking messages with optional tool name */
start(callback: (message: string) => void, toolName?: string): void {
- // Stop any existing thinking before starting new one
this.stop();
this.currentType = toolName ? 'tools' : 'general';
@@ -200,12 +140,9 @@ class ThinkingMessageManager {
this.toolName = formatFunctionName(toolName);
}
- // Show first message immediately
const initialMessage = this.getCurrentMessage();
callback(initialMessage);
- // Start interval only for general and function types
-
const intervalTime = this.currentType === 'tools' ? 5000 : 3000;
this.intervalId = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.getMessagesArray().length;
@@ -214,9 +151,7 @@ class ThinkingMessageManager {
}, intervalTime);
}
- /**
- * Stops thinking messages and clears state
- */
+ /** Stops thinking messages and clears state */
stop(): void {
if (this.intervalId) {
clearInterval(this.intervalId);
@@ -228,9 +163,6 @@ class ThinkingMessageManager {
this.callback = () => {};
}
- /**
- * Gets current message with placeholders replaced
- */
private getCurrentMessage(): string {
const messages = this.getMessagesArray();
const messageTemplate = messages[this.currentIndex];
@@ -242,9 +174,6 @@ class ThinkingMessageManager {
return messageTemplate;
}
- /**
- * Gets messages array for current type
- */
private getMessagesArray(): string[] {
switch (this.currentType) {
case 'tools':
@@ -256,19 +185,16 @@ class ThinkingMessageManager {
}
}
}
-/**
- * Creates a singleton instance of ThinkingMessageManager
- */
+
+/** Creates a new ThinkingMessageManager instance */
export const createThinkingManager = (): ThinkingMessageManager => new ThinkingMessageManager();
/**
- * Processes a chunk from the stream and extracts relevant information
- *
+ * Processes a stream chunk and extracts relevant information
* @param chunk - Stream chunk to process
- * @returns Processed information
+ * @returns Processed chunk data
*/
export const processStreamChunk = (chunk: IStreamChunk) => {
- // When isError is true, the error message is in the content field
const errorMessage = chunk.error || (chunk.isError ? chunk.content : null);
return {