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
Enhance Chat API Client and Related Hooks
Salman-Ahamed661db1163948
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 64a5de24..ba8fd397 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@@ -20,20 +20,15 @@ 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';/*** Default configuration for the Chat API Client*/const DEFAULT_CONFIG: IAPIConfig = {baseUrl: '/api/page/chat',- defaultHeaders: {- 'Content-Type': 'application/json',- },- timeout: 300000, // 5 minutes- retry: {- attempts: 0, // No retry by default for streaming- delay: 1000,- },+ defaultHeaders: { 'Content-Type': 'application/json' },};/**@@ -102,7 +97,7 @@ export class ChatAPIClient {}// State management for stream processing- const accumulatedData = '';+ let accumulatedData = ''; // eslint-disable-line prefer-constlet reader: ReadableStreamDefaultReader<Uint8Array> | null = null;try {@@ -418,11 +413,47 @@ export class ChatAPIClient {}}+ /**+ * Creates a new chat conversation+ *+ * @param params - Chat creation parameters+ * @returns Promise resolving to the created chat data+ * @throws {Error} If the request fails+ *+ * @example+ * ```typescript+ * const chat = await client.createChat({+ * conversation: {+ * summary: '',+ * chunkSize: 100,+ * lastChunkID: '0',+ * label: 'New Chat',+ * aiAgentId: 'agent-123',+ * },+ * });+ * ```+ */+ async createChat(params: CreateChatRequest): Promise<CreateChatsResponse> {+ const response = await fetch(`${this.config.baseUrl}/new`, {+ method: 'POST',+ headers: this.config.defaultHeaders,+ body: JSON.stringify(params),+ });++ if (!response.ok) {+ const errorData = await this.parseErrorResponse(response);+ throw new Error(errorData.message || `Failed to create chat: ${response.statusText}`);+ }++ 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@@ -431,27 +462,36 @@ export class ChatAPIClient {* // Use attachment.url in chat message* ```*/- async uploadFile(file: File, agentId: string): Promise<IFileAttachment> {+ async uploadFile(file: File, agentId: string, chatId?: string): Promise<IFileAttachment> {const formData = new FormData();formData.append('file', file);- formData.append('agentId', agentId);++ const headers: Record<string, string> = {+ 'X-AGENT-ID': agentId,+ ...(chatId ? { 'x-conversation-id': chatId } : {}),+ };try {- const response = await fetch(`${this.config.baseUrl}/upload`, {+ 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}`);- }+ 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: data.url || data.publicUrl,+ url: fileUrl || '',name: file.name,- type: file.type,+ type: fileType,size: file.size,};} catch (error) {@@ -460,49 +500,4 @@ export class ChatAPIClient {);}}-- /**- * Updates the API configuration- *- * @param config - Partial configuration to update- *- * @example- * ```typescript- * client.updateConfig({ timeout: 60000 });- * ```- */- updateConfig(config: Partial<IAPIConfig>): void {- this.config = { ...this.config, ...config };- }-- /**- * Gets current API configuration- *- * @returns Current configuration- */- getConfig(): IAPIConfig {- return { ...this.config };- }}--/**- * Default singleton instance for convenience- */-export const chatAPI = new ChatAPIClient();--/**- * Factory function to create a new ChatAPIClient instance- *- * @param config - Optional configuration- * @returns New ChatAPIClient instance- *- * @example- * ```typescript- * const customClient = createChatClient({- * baseUrl: '/custom/endpoint',- * });- * ```- */-export const createChatClient = (config?: Partial<IAPIConfig>) => {- return new ChatAPIClient(config);-};diff --git a/packages/app/src/react/features/ai-chat/clients/index.ts b/packages/app/src/react/features/ai-chat/clients/index.tsindex 4ca55908..6d31ead8 100644--- a/packages/app/src/react/features/ai-chat/clients/index.ts+++ b/packages/app/src/react/features/ai-chat/clients/index.ts@@ -1,22 +1,19 @@-import { CreateChatRequest, FetchChatMessagesRequest } from '@react/shared/types/api-payload.types';--export const createChat = async (params: CreateChatRequest) => {- const response = await fetch('/api/page/chat/new', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(params),- });- return response.json();-};--export const fetchChatMessages = async (params: FetchChatMessagesRequest) => {- const { agentId, chatId, page, limit } = params;- const response = await fetch(`/api/page/chat/messages?page=${page}&limit=${limit}`, {- headers: { 'x-agent-id': agentId, 'x-conversation-id': chatId },- });- return response.json();-};-+/**+ * Updates agent settings+ *+ * @param agentId - Agent ID+ * @param settings - Settings object with key and value+ * @returns Promise resolving to the updated settings data+ * @throws {Error} If the request fails+ *+ * @example+ * ```typescript+ * await updateAgentSettings('agent-123', {+ * key: 'chatGptModel',+ * value: 'gpt-4',+ * });+ * ```+ */export const updateAgentSettings = async (agentId: string,settings: { key: string; value: string },@@ -27,16 +24,34 @@ export const updateAgentSettings = async (body: JSON.stringify(settings),});- if (!response.ok) throw new Error('Failed to update agent settings');+ if (!response.ok) {+ throw new Error(`Failed to update agent settings: ${response.statusText}`);+ }return response.json();};-// delete agent settings+/**+ * Deletes agent settings by key+ *+ * @param agentId - Agent ID+ * @param key - Settings key to delete+ * @returns Promise resolving to the deletion response+ * @throws {Error} If the request fails+ *+ * @example+ * ```typescript+ * await deleteAgentSettings('agent-123', 'chatGptModel');+ * ```+ */export const deleteAgentSettings = async (agentId: string, key: string) => {const response = await fetch(`/api/page/agent_settings/ai-agent/${agentId}/settings/${key}`, {method: 'DELETE',});- if (!response.ok) throw new Error('Failed to delete agent settings');++ if (!response.ok) {+ throw new Error(`Failed to delete agent settings: ${response.statusText}`);+ }+return response.json();};diff --git a/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx b/packages/app/src/react/features/ai-chat/contexts/chat-context.tsxnew file mode 100644index 00000000..b1c0fb09--- /dev/null+++ b/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx@@ -0,0 +1,9 @@+import { createContext } from 'react';++export interface IChatContext {+ agentId: string;+}++export const ChatContext = createContext<IChatContext>({+ agentId: '',+});diff --git a/packages/app/src/react/features/ai-chat/contexts/index.new.tsx b/packages/app/src/react/features/ai-chat/contexts/index.new.tsxnew file mode 100644index 00000000..12dcbf2b--- /dev/null+++ b/packages/app/src/react/features/ai-chat/contexts/index.new.tsx@@ -0,0 +1,15 @@+import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat-context';+import { FC, ReactNode, useMemo, useState } from 'react';++interface IProps {+ children: ReactNode;+}++export const ChatContextProvider: FC<IProps> = ({ children }) => {+ const [agentId] = useState('');++ // Memoize the store to avoid unnecessary re-renders+ const values: IChatContext = useMemo(() => ({ agentId }), [agentId]);++ return <ChatContext.Provider value={values}>{children}</ChatContext.Provider>;+};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.tsindex faff391a..5dd789fc 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@@ -1,4 +1,4 @@-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { MutableRefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useNavigate } from 'react-router-dom';import {@@ -12,14 +12,14 @@ import { IChatMessage, IMessageFile } from '@react/features/ai-chat/types/chat.timport { useAgent } from '@react/shared/hooks/agent';import { Observability } from '@shared/observability';import { EVENTS } from '@shared/posthog/constants/events';+import { ChatInputRef } from '../components';/*** Configuration options for useAgentChatContext hook*/export interface IUseAgentChatContextConfig {agentId: string; // Agent ID for the chat session- onChatReady?: () => void; // Callback when chat is ready- onChatCleared?: () => void; // Callback when chat session is cleared+ inputRef?: MutableRefObject<ChatInputRef>; // Ref to the chat input}/**@@ -78,7 +78,7 @@ export interface IUseAgentChatContextReturn {* ```tsx* const { chatContextValue, agent, isLoading } = useAgentChatContext({* agentId: '123',- * onChatReady: () => console.log('Chat ready!'),+ * inputRef: chatInputRef,* });** return (@@ -91,7 +91,7 @@ export interface IUseAgentChatContextReturn {export const useAgentChatContext = (config: IUseAgentChatContextConfig,): IUseAgentChatContextReturn => {- const { agentId, onChatReady, onChatCleared } = config;+ const { agentId, inputRef } = config;const navigate = useNavigate();// Internal refs for tracking state@@ -238,12 +238,12 @@ export const useAgentChatContext = (await createNewChatSession();// Trigger callback- onChatCleared?.();+ inputRef?.current?.focus();// Track observability eventsObservability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);- }, [createNewChatSession, clearChatMessages, clearFiles, stopGenerating, onChatCleared]);+ }, [createNewChatSession, clearChatMessages, clearFiles, stopGenerating, inputRef]);// ============================================================================// LIFECYCLE EFFECTS@@ -260,7 +260,7 @@ export const useAgentChatContext = (// This ensures fresh conversation every time user loads the pagehasInitializedChatRef.current = true;- createNewChatSession().then(() => onChatReady?.());+ createNewChatSession().then(() => inputRef?.current?.focus());}// eslint-disable-next-line react-hooks/exhaustive-deps}, [agentSettings, agent, agentId]); // Only depend on core values, not callbacksdiff --git a/packages/app/src/react/features/ai-chat/hooks/use-create-chat.ts b/packages/app/src/react/features/ai-chat/hooks/use-create-chat.tsindex 6578c1ac..f942505a 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-create-chat.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-create-chat.ts@@ -1,26 +1,24 @@import { useMutation } from '@tanstack/react-query';-import { createChat } from '@react/features/ai-chat/clients';+import { ChatAPIClient } from '@react/features/ai-chat/clients/chat-api.client';import { queryClient } from '@react/shared/query-client';import type { CreateChatRequest } from '@react/shared/types/api-payload.types';import type { CreateChatsResponse } from '@react/shared/types/api-results.types';-export const agentRequestKeys = {- CHAT_LIST_QUERY: ['get', '/api/page/chat/list'],- AGENT_LIST_QUERY: ['get', '/api/page/agents/agents'],- CHAT_DELETE_MUTATION: ['delete', '/api/page/chat/'],- CHAT_UPDATE_MUTATION: ['update', '/api/page/chat/'],- CHAT_CREATE_MUTATION: ['post', '/api/page/chat/new'],- CONVERSATION_QUERY: ['get', '/api/page/chat/messages'],-};+// Query keys for chat operations+const CHAT_CREATE_MUTATION = ['post', '/api/page/chat/new'];+const CHAT_LIST_QUERY = ['get', '/api/page/chat/list'];++// Create a singleton instance for chat operations+const chatClient = new ChatAPIClient();export const useCreateChatMutation = () =>useMutation<CreateChatsResponse, Error, CreateChatRequest>(- agentRequestKeys.CHAT_CREATE_MUTATION,- (params) => createChat(params),+ CHAT_CREATE_MUTATION,+ (params) => chatClient.createChat(params),{onSuccess: () => {- queryClient.invalidateQueries(agentRequestKeys.CHAT_LIST_QUERY); // reset cache, if any, of chat list+ queryClient.invalidateQueries(CHAT_LIST_QUERY); // reset cache, if any, of chat list},},);diff --git a/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts b/packages/app/src/react/features/ai-chat/hooks/use-fileupload.tsindex 2a816539..d81620e7 100644--- a/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts+++ b/packages/app/src/react/features/ai-chat/hooks/use-fileupload.ts@@ -1,12 +1,12 @@/* eslint-disable no-unused-vars */-import { ChangeEvent, useCallback, useEffect, useState } from 'react';+import { ChangeEvent, useCallback, useEffect, useMemo, useState } from 'react';+import { ChatAPIClient } from '@react/features/ai-chat/clients/chat-api.client';import { IMessageFile } from '@react/features/ai-chat/types/chat.types';import {createFileMetadata,deleteFile,FILE_LIMITS,- uploadFile,validateSingleFile,} from '@react/features/ai-chat/utils/file';@@ -44,6 +44,9 @@ export const useFileUpload = (params?: {const isUploadInProgress = uploadingFiles.size > 0;+ // Create ChatAPIClient instance for file uploads (memoized to avoid recreating)+ const chatClient = useMemo(() => new ChatAPIClient(), []);+// Auto-clear upload error after 5 seconds when it becomes visibleuseEffect(() => {let timeoutId: NodeJS.Timeout;@@ -112,39 +115,33 @@ export const useFileUpload = (params?: {})),]);- // Upload files concurrently+ // Upload files concurrently using ChatAPIClientconst uploadPromises = filesToUpload.map(async ({ file, id }) => {try {- const result = await uploadFile(file, agentId, chatId);-- if (result.success) {- const data = result.data as {- files?: Array<{ url?: string; mimetype?: string }>;- file?: { url?: string; type?: string };- };- const runtimeFile = data?.files?.[0];- setFiles((prevFiles) =>- prevFiles.map((f) =>- f.id === id- ? {- ...f,- metadata: {- ...f.metadata,- // Do not set key for runtime uploads (avoid delete attempts)- publicUrl: runtimeFile?.url || data?.file?.url,- fileType: runtimeFile?.mimetype || data?.file?.type,- isUploading: false,- },- }- : f,- ),- );- } else {- throw new Error(result.error);- }- } catch {+ const attachment = await chatClient.uploadFile(file, agentId, chatId);++ setFiles((prevFiles) =>+ prevFiles.map((f) =>+ f.id === id+ ? {+ ...f,+ metadata: {+ ...f.metadata,+ // Do not set key for runtime uploads (avoid delete attempts)+ publicUrl: attachment.url,+ fileType: attachment.type,+ isUploading: false,+ },+ }+ : f,+ ),+ );+ } catch (error) {setFiles((prevFiles) => prevFiles.filter((f) => f.id !== id));- setUploadError({ show: true, message: 'Failed to upload file' });+ setUploadError({+ show: true,+ message: error instanceof Error ? error.message : 'Failed to upload file',+ });} finally {setUploadingFiles((prev) => {const next = new Set(prev);@@ -157,7 +154,7 @@ export const useFileUpload = (params?: {await Promise.all(uploadPromises);}},- [files.length, agentId, chatId],+ [files.length, agentId, chatId, chatClient],);const handleFileChange = useCallback(diff --git a/packages/app/src/react/features/ai-chat/hooks/use-store.tsx b/packages/app/src/react/features/ai-chat/hooks/use-store.tsxnew file mode 100644index 00000000..c6026217--- /dev/null+++ b/packages/app/src/react/features/ai-chat/hooks/use-store.tsx@@ -0,0 +1,10 @@+import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat-context';+import { useContext } from 'react';++export const useChatContext = () => useContext(ChatContext);++export const useChatContextValue = <T extends keyof IChatContext>(state: T): IChatContext[T] => {+ const store = useContext(ChatContext);+ if (!store) throw new Error('ChatContext not found');+ return store[state];+};diff --git a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsxindex da486eb1..4ca78476 100644--- a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx+++ b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx@@ -41,11 +41,7 @@ const AgentChatPage = () => {chatContextValue,sharedMessagesHistory,handleFileDrop,- } = useAgentChatContext({- agentId: agentId || '',- onChatReady: () => chatInputRef.current?.focus(), // Focus input when chat is ready- onChatCleared: () => chatInputRef.current?.focus(), // Focus input after clearing chat- });+ } = useAgentChatContext({ agentId: agentId || '', inputRef: chatInputRef });// ============================================================================// SCROLL BEHAVIORdiff --git a/packages/app/src/react/features/ai-chat/utils/chat-performance-monitor.ts b/packages/app/src/react/features/ai-chat/utils/chat-performance-monitor.tsindex 4ab9b127..c990dc9f 100644--- a/packages/app/src/react/features/ai-chat/utils/chat-performance-monitor.ts+++ b/packages/app/src/react/features/ai-chat/utils/chat-performance-monitor.ts@@ -5,7 +5,6 @@* PRODUCTION-SAFE monitoring tool that helps identify bottlenecks in:* - Network latency (server response time)* - Chunk processing time- * - UI render time** Features:* - Zero performance impact when disabled@@ -35,7 +34,6 @@ interface ChunkMetric {chunkIndex: number; // Sequential index of this chunk in the streamnetworkTime?: number; // Time elapsed since previous chunk (milliseconds)processingTime?: number; // Time spent processing/parsing the chunk (milliseconds)- renderTime?: number; // Time spent rendering the chunk in UI (milliseconds)chunkSize: number; // Size of chunk data in bytestype: 'content' | 'thinking' | 'tool' | 'debug'; // Type of content in this chunk}@@ -47,7 +45,6 @@ interface PerformanceMetrics {totalChunks: number; // Total number of chunks receivedaverageNetworkTime: number; // Average time between chunks (milliseconds)averageProcessingTime: number; // Average processing time per chunk (milliseconds)- averageRenderTime: number; // Average render time per chunk (milliseconds)totalDuration: number; // Total stream duration (milliseconds)slowestChunk: ChunkMetric | null; // Chunk with highest total latencychunksPerSecond: number; // Throughput in chunks per second@@ -189,26 +186,6 @@ class PerformanceMonitor {}}- /**- * Records UI render time- * @param renderTime - Time taken to render in milliseconds- */- recordRenderTime(renderTime: number): void {- if (!this.enabled) return;-- const lastMetric = this.metrics[this.metrics.length - 1];- if (lastMetric) {- lastMetric.renderTime = renderTime;-- if (renderTime > 16.67) {- // More than 1 frame at 60fps- this.warn(- `⚠️ SLOW RENDER #${lastMetric.chunkIndex}: ${renderTime.toFixed(2)}ms (dropped frames!)`,- );- }- }- }-/*** Ends stream and shows summary* Displays comprehensive performance report in console@@ -226,14 +203,12 @@ class PerformanceMonitor {this.log('\n📊 PERFORMANCE BREAKDOWN:');this.log(` 🌐 Network (avg): ${metrics.averageNetworkTime.toFixed(2)}ms`);this.log(` ⚙️ Processing (avg): ${metrics.averageProcessingTime.toFixed(2)}ms`);- this.log(` 🎨 Rendering (avg): ${metrics.averageRenderTime.toFixed(2)}ms`);if (metrics.slowestChunk) {this.log('\n🐌 SLOWEST CHUNK:');this.log(` Index: #${metrics.slowestChunk.chunkIndex}`);this.log(` Network: ${metrics.slowestChunk.networkTime?.toFixed(2)}ms`);this.log(` Processing: ${metrics.slowestChunk.processingTime?.toFixed(2)}ms`);- this.log(` Render: ${metrics.slowestChunk.renderTime?.toFixed(2)}ms`);this.log(` Size: ${metrics.slowestChunk.chunkSize} bytes`);}@@ -246,7 +221,7 @@ class PerformanceMonitor {* @param metrics - Performance metrics to analyze*/private identifyBottleneck(metrics: PerformanceMetrics): void {- const { averageNetworkTime, averageProcessingTime, averageRenderTime } = metrics;+ const { averageNetworkTime, averageProcessingTime } = metrics;this.log('\n🎯 BOTTLENECK ANALYSIS:');@@ -268,16 +243,7 @@ class PerformanceMonitor {);}- if (averageRenderTime > 16.67) {- this.error(- '❌ UI RENDERING BOTTLENECK DETECTED!',- `\n Average render time: ${averageRenderTime.toFixed(2)}ms`,- '\n ➡️ Issue: UI updates are slow (dropping frames)',- '\n ➡️ Check: Component re-renders, DOM operations, React memoization',- );- }-- if (averageNetworkTime <= 50 && averageProcessingTime <= 30 && averageRenderTime <= 16.67) {+ if (averageNetworkTime <= 50 && averageProcessingTime <= 30) {this.log('✅ NO BOTTLENECKS DETECTED! Performance is optimal.');}}@@ -293,7 +259,6 @@ class PerformanceMonitor {totalChunks: 0,averageNetworkTime: 0,averageProcessingTime: 0,- averageRenderTime: 0,totalDuration: 0,slowestChunk: null,chunksPerSecond: 0,@@ -305,7 +270,6 @@ class PerformanceMonitor {// Calculate averagesconst networkTimes = this.metrics.map((m) => m.networkTime || 0).filter((t) => t > 0);const processingTimes = this.metrics.map((m) => m.processingTime || 0).filter((t) => t > 0);- const renderTimes = this.metrics.map((m) => m.renderTime || 0).filter((t) => t > 0);const averageNetworkTime =networkTimes.length > 0 ? networkTimes.reduce((a, b) => a + b, 0) / networkTimes.length : 0;@@ -313,15 +277,11 @@ class PerformanceMonitor {processingTimes.length > 0? processingTimes.reduce((a, b) => a + b, 0) / processingTimes.length: 0;- const averageRenderTime =- renderTimes.length > 0 ? renderTimes.reduce((a, b) => a + b, 0) / renderTimes.length : 0;// Find slowest chunk (by total time)const slowestChunk = this.metrics.reduce((slowest, current) => {- const currentTotal =- (current.networkTime || 0) + (current.processingTime || 0) + (current.renderTime || 0);- const slowestTotal =- (slowest.networkTime || 0) + (slowest.processingTime || 0) + (slowest.renderTime || 0);+ const currentTotal = (current.networkTime || 0) + (current.processingTime || 0);+ const slowestTotal = (slowest.networkTime || 0) + (slowest.processingTime || 0);return currentTotal > slowestTotal ? current : slowest;}, this.metrics[0]);@@ -330,7 +290,6 @@ class PerformanceMonitor {totalChunks,averageNetworkTime,averageProcessingTime,- averageRenderTime,totalDuration,slowestChunk,chunksPerSecond: (totalChunks / totalDuration) * 1000,diff --git a/packages/app/src/react/features/ai-chat/utils/file.ts b/packages/app/src/react/features/ai-chat/utils/file.tsindex a653a84e..c3449496 100644--- a/packages/app/src/react/features/ai-chat/utils/file.ts+++ b/packages/app/src/react/features/ai-chat/utils/file.ts@@ -9,30 +9,6 @@ export const FILE_LIMITS = {ACCEPTED_TYPES: ['*/*'], // Accept all file types like chatbot} as const;-/**- * Supported file types for preview- */-export const FILE_TYPES = {- PDF: 'application/pdf',- IMAGE: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'] as const,- CSV: ['text/csv', 'application/csv'] as const,- EXCEL: [- 'application/vnd.ms-excel',- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',- ] as const,-} as const;--type ImageMimeType = (typeof FILE_TYPES.IMAGE)[number];--/**- * Checks if the file is an image- * @param {File} file - File to check- * @returns {boolean} True if file is an image- */-export const isImageFile = (file: File): boolean => {- return FILE_TYPES.IMAGE.includes(file.type as ImageMimeType);-};-/*** Gets local preview URL for a file if possible* @param {File} file - File to get preview for@@ -45,33 +21,6 @@ export const getLocalPreviewUrl = (file: File): string | null => {return null;};-/**- * Validates files against size, type and count limits- * @param newFiles Array of files to validate- * @param existingFileCount Number of files already attached- * @returns Error message string if validation fails, null if validation passes- */-export const validateFiles = (newFiles: File[], existingFileCount: number): string | null => {- // Check total file count- const totalFileCount = existingFileCount + newFiles.length;- if (totalFileCount > FILE_LIMITS.MAX_ATTACHED_FILES) {- return `Maximum ${FILE_LIMITS.MAX_ATTACHED_FILES} files allowed`;- }-- // Check each file- for (const file of newFiles) {- // Check file size- if (file.size > FILE_LIMITS.MAX_FILE_SIZE) {- return `File ${file.name} exceeds maximum size of 5MB`;- }-- // Accept all file types - no file type validation needed- // Since we're accepting */* all file types are allowed- }-- return null;-};-/*** Validates a single file against size constraints only* @param file The file to validate@@ -88,40 +37,6 @@ export const validateSingleFile = (file: File): string | null => {return null;};-/**- * Uploads a file to the server- * @param file The file to upload- * @returns The uploaded file data or error- */-export const uploadFile = async (- file: File,- agentId: string,- chatId?: string,-): Promise<{ success: boolean; data?: Record<string, unknown>; error?: string }> => {- try {- const formData = new FormData();- formData.append('file', file);-- const response = await fetch('/api/page/chat/upload', {- method: 'POST',- body: formData,- headers: {- 'X-AGENT-ID': agentId,- ...(chatId ? { 'x-conversation-id': chatId } : {}),- },- });-- if (!response.ok) {- throw new Error('Failed to upload file');- }-- const data = await response.json();- return { success: true, data };- } catch (error) {- return { success: false, error: error.message };- }-};-/*** Deletes a file from the server* @param key The file key to deletediff --git a/packages/app/src/react/features/ai-chat/utils/index.ts b/packages/app/src/react/features/ai-chat/utils/index.tsindex ae651993..cb352b60 100644--- a/packages/app/src/react/features/ai-chat/utils/index.ts+++ b/packages/app/src/react/features/ai-chat/utils/index.ts@@ -1,602 +1,4 @@-/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any */import { IMessageFile } from '@react/features/ai-chat/types/chat.types';-import config from '@src/builder-ui/config';--type GenerateResponseInput = {- agentId: string;- chatId: string;- query: string;- attachments?: { url: string; name?: string; type?: string; size?: number }[];- signal: AbortSignal;- onResponse: (value: string, errorInfo?: { isError?: boolean; errorType?: string }) => void;- onStart: () => void;- onEnd: () => void;- onThinking?: (thinking: { message: string }) => void;-};--type ResponseFormat = {- role?: string;- content?: string;- debug?: string;- title?: string;- status_message?: string;- function?: string;- function_call?: { name?: string; arguments?: any[] };- error?: string;- isError?: boolean;- errorType?: string;-};--// Function-specific thinking messages that cycle every 5 seconds-const FUNCTION_THINKING_MESSAGES = [- 'Using skill: {functionName}',- 'Still working on {functionName}',- 'Skills are like work, sometimes they take a while.',- 'Still working on {functionName}',- 'Double checking',- 'This is taking longer than usual. You can try waiting, or refresh the page.',-];--// General thinking messages that cycle every 3 seconds-const GENERAL_THINKING_MESSAGES = [- 'Thinking',- 'Still thinking',- 'Almost there',- 'Double checking',- 'Almost done',- 'This is taking longer than usual. You can try waiting, or refresh the page.',-];--// Thinking message types-type ThinkingType = 'general' | 'function' | 'status';--// Unified thinking message manager-class UnifiedThinkingManager {- private currentType: ThinkingType | null = null;- private currentIndex: number = 0;- private intervalId: NodeJS.Timeout | null = null;- private functionName: string = '';- private statusMessage: string = '';- private onThinking: ((thinking: { message: string }) => void) | null = null;-- start(- type: ThinkingType,- onThinking: (thinking: { message: string }) => void,- functionName?: string,- statusMessage?: string,- ): void {- // Priority system: status > function > general- const priorityOrder = { status: 3, function: 2, general: 1 };- const currentPriority = this.currentType ? priorityOrder[this.currentType] : 0;- const newPriority = priorityOrder[type];-- // Only start new thinking if it has higher or equal priority- if (newPriority < currentPriority) {- return; // Don't override higher priority thinking- }-- // Stop any existing thinking- this.stop();-- this.currentType = type;- this.onThinking = onThinking;- this.currentIndex = 0;-- if (type === 'function' && functionName) {- this.functionName = functionName;- }- if (type === 'status' && statusMessage) {- this.statusMessage = statusMessage;- }-- // Show first message immediately- const initialMessage = this.getCurrentMessage();- onThinking({ message: initialMessage });-- // Start interval only for general and function types- if (type !== 'status') {- const intervalTime = type === 'function' ? 5000 : 3000;- this.intervalId = setInterval(() => {- this.currentIndex = (this.currentIndex + 1) % this.getMessagesArray().length;- const message = this.getCurrentMessage();- onThinking({ message });- }, intervalTime);- }- }-- updateStatus(newStatusMessage: string): void {- if (this.currentType === 'status' && this.onThinking) {- // Format the status message before storing and displaying- const formattedMessage = chatUtils.formatStatusMessage(newStatusMessage);- this.statusMessage = formattedMessage;- this.onThinking({ message: formattedMessage });- }- }-- stop(): void {- if (this.intervalId) {- clearInterval(this.intervalId);- this.intervalId = null;- }- this.currentType = null;- this.currentIndex = 0;- this.functionName = '';- this.statusMessage = '';- this.onThinking = null;- }-- private getCurrentMessage(): string {- if (this.currentType === 'status') {- return this.statusMessage;- }-- const messages = this.getMessagesArray();- const messageTemplate = messages[this.currentIndex];-- if (this.currentType === 'function') {- return messageTemplate.replace('{functionName}', this.functionName);- }-- return messageTemplate;- }-- private getMessagesArray(): string[] {- switch (this.currentType) {- case 'function':- return FUNCTION_THINKING_MESSAGES;- case 'general':- return GENERAL_THINKING_MESSAGES;- default:- return [];- }- }-- getCurrentType(): ThinkingType | null {- return this.currentType;- }-}--export const chatUtils = {- // Unified thinking message manager- thinkingManager: new UnifiedThinkingManager(),-- /**- * Handles status message display with priority system- * @param statusMessage - The status message to display- * @param onThinking - Callback function for thinking updates- * @returns true if status message was handled, false otherwise- */- handleStatusMessage: (- statusMessage: string | undefined,- onThinking: (thinking: { message: string }) => void,- ): boolean => {- if (statusMessage) {- // Format the status message for better display- const formattedStatusMessage = chatUtils.formatStatusMessage(statusMessage);- chatUtils.thinkingManager.start('status', onThinking, undefined, formattedStatusMessage);- return true;- }- return false;- },-- /**- * Extracts function name from debug message for user-friendly display- * @param debugContent - The raw debug message content- * @returns The extracted function name or null if not found- */- extractFunctionNameFromDebug: (debugContent: string): string | null => {- // Multiple patterns to extract function name from debug messages:- // 1. "[ID] Function Call : name" - from toolsInfoHandler- // 2. "[ID] Call Response : name" - from afterToolCallHandler- // 3. "Function Call : name" - without ID- // 4. "Call Response : name" - without ID- // 5. "name" - just function name alone- const patterns = [- /(?:\[\w+\]\s+Function Call\s*:\s*)([a-zA-Z_][a-zA-Z0-9_]*)/,- /(?:\[\w+\]\s+Call Response\s*:\s*)([a-zA-Z_][a-zA-Z0-9_]*)/,- /(?:Function Call\s*:\s*)([a-zA-Z_][a-zA-Z0-9_]*)/,- /(?:Call Response\s*:\s*)([a-zA-Z_][a-zA-Z0-9_]*)/,- /^([a-zA-Z_][a-zA-Z0-9_]*)$/, // Just function name alone (like 'get_destinations')- ];-- const result =- patterns- .map((pattern) => debugContent.match(pattern))- .find((match) => match && match[1])- ?.at(1) ?? null;-- return result;- },-- /**- * Formats function name for user-friendly display- * @param functionName - The raw function name- * @returns Formatted function name for display- */- formatFunctionNameForDisplay: (functionName: string): string => {- // Convert snake_case to Title Case for better readability- const formatted = functionName- .split('_')- .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())- .join(' ');-- return formatted;- },-- /**- * Formats status message with proper function name and duration display- * @param statusMessage - The raw status message containing function names and durations in curly braces- * @returns Formatted status message for user display- */- formatStatusMessage: (statusMessage: string): string => {- 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 chatUtils.formatFunctionNameForDisplay(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`;- });-- return formatted;- },- getChatStreamURL: (agentId: string, isLocal = false) => {- const remoteDomain = config.env.IS_DEV ? 'agent.stage.smyth.ai' : 'agent.a.smyth.ai';- return isLocal- ? `http://${agentId}.localagent.stage.smyth.ai:3000`- : `https://${agentId}.${remoteDomain}`;- },- splitDataToJSONObjects: (data: string) => {- // Handle empty or invalid data- if (!data || typeof data !== 'string') return [];-- // Clean the data first - remove any incomplete JSON chunks- const cleanData = data.trim();- if (!cleanData) return [];-- // Split by '}{' but handle edge cases- 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 += '}';- }-- return cleanStr;- })- .filter(Boolean) as string[];-- const result = jsonStrings- .map((str) => {- try {- // Additional validation before parsing- if (!str || str.length < 2) return null;-- // Check if it looks like JSON- if (!str.startsWith('{') || !str.endsWith('}')) return null;-- return JSON.parse(str) as ResponseFormat;- } catch (error) {- // Silently skip invalid JSON instead of logging errors- return null;- }- })- .filter(Boolean);-- return result;- },- generateResponse: async (input: GenerateResponseInput) => {- let message = '';-- // Enhanced Message State Management- type MessageState = 'initial' | 'debug' | 'final';- let messageState: MessageState = 'initial';-- // Smooth Transition Handler- const handleMessageTransition = (newState: MessageState) => {- if (messageState === 'initial' && newState === 'debug') {- // Don't clear message immediately when debug starts - keep the processing message- // The message will be cleared only when debug ends and content starts arriving- } else if (messageState === 'debug' && newState === 'final') {- // Clear and prepare for final content - only when debug is completely finished- // Don't clear message here - let content accumulate naturally- // Add a line break to separate thinking from content if message doesn't end with newline- if (message.length > 0 && !message.endsWith('\n')) {- message = `${message}\n`;- }- input.onResponse(''); // Clear UI display to show fresh content- }- messageState = newState;- };-- // Enhanced Error Handler- const handleErrorGracefully = (error: string) => {- const errorMessage = 'Sorry, something went wrong. Please try again.';- input.onResponse(errorMessage);- };-- try {- let openAiResponse: Response;- try {- openAiResponse = await fetch('/api/page/chat/stream', {- method: 'POST',- headers: {- 'Content-Type': 'application/json',- 'X-AGENT-ID': input.agentId,- 'x-conversation-id': input.chatId,- 'x-enable-meta-messages': 'true',- },- body: JSON.stringify({- message: input.query,- attachments: input.attachments,- }),- signal: input.signal,- });- } catch (fetchError) {- throw new Error(- `Network request failed: ${fetchError.message || fetchError.error || 'Unknown error'}`,- );- }-- if (!openAiResponse || openAiResponse?.status !== 200) {- try {- const errorData = await openAiResponse.json();- const errorMessage = errorData?.error || 'Failed to get a valid response';- throw new Error(errorMessage);- } catch (parseError) {- // If JSON parsing fails, use a generic error message- throw new Error(`HTTP ${openAiResponse?.status}: Failed to get a valid response`);- }- }-- const reader = openAiResponse.body?.getReader();- if (!reader) {- throw new Error('Failed to get response reader - response body is null');- }- let accumulatedData = '';-- input.onStart();-- while (true) {- try {- const { done, value } = await reader.read();-- if (input.signal.aborted) {- reader.cancel();- throw new DOMException('Aborted', 'AbortError');- }-- if (done) break;-- const decodedValue = new TextDecoder().decode(value);- accumulatedData += decodedValue;- } catch (streamError) {- // Handle stream reading errors- reader.cancel();- throw new Error(`Stream reading failed: ${streamError.message}`);- }-- // Only process if we have complete JSON objects- let jsonObjects: ResponseFormat[] = [];- try {- jsonObjects = chatUtils.splitDataToJSONObjects(accumulatedData);- } catch (parseError) {- // Handle JSON parsing errors gracefully - skip this chunk and continue processing- continue;- }-- // First pass: Check for state transitions and start thinking if needed- for (const jsonObject of jsonObjects) {- if (jsonObject.debug && messageState === 'initial') {- handleMessageTransition('debug');- // Start general thinking when debug begins- if (input.onThinking) {- chatUtils.thinkingManager.start('general', input.onThinking);- }- break;- }- }-- // Second pass: Process all messages- for (const jsonObject of jsonObjects) {- if (jsonObject.error) {- handleErrorGracefully(jsonObject.error);- throw new Error(jsonObject.error);- }-- // Check for status_message at the top level - highest priority- if (- input.onThinking &&- chatUtils.handleStatusMessage(jsonObject.status_message, input.onThinking)- ) {- // Status message handled, continue to next object- continue;- }-- if (jsonObject.debug) {- // Handle debug messages with dynamic thinking system- const debugContent = jsonObject.debug;-- // Try to extract function name from debug message- let functionName = chatUtils.extractFunctionNameFromDebug(debugContent);-- // If debug content is just a function name (like 'get_destinations'), use it directly- if (!functionName && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(debugContent.trim())) {- functionName = debugContent.trim();- }-- if (functionName) {- // If we can extract a function name, use dynamic thinking messages- const formattedFunctionName = chatUtils.formatFunctionNameForDisplay(functionName);-- // Start function-specific thinking- if (input.onThinking) {- chatUtils.thinkingManager.start(- 'function',- input.onThinking,- formattedFunctionName,- );- }- } else if (jsonObject.function) {- // If function field exists, use it directly- const formattedFunctionName = chatUtils.formatFunctionNameForDisplay(- jsonObject.function,- );-- // Start function-specific thinking- if (input.onThinking) {- chatUtils.thinkingManager.start(- 'function',- input.onThinking,- formattedFunctionName,- );- }- } else {- // Check for status_message first - highest priority- if (- input.onThinking &&- chatUtils.handleStatusMessage(jsonObject.status_message, input.onThinking)- ) {- // Status message handled, skip function name extraction- } else {- // Try to extract function name from debug title if not found in debug content- const debugTitle = jsonObject.title || '';- const functionNameFromTitle = chatUtils.extractFunctionNameFromDebug(debugTitle);-- if (functionNameFromTitle) {- const formattedFunctionName =- chatUtils.formatFunctionNameForDisplay(functionNameFromTitle);-- // Start function-specific thinking- if (input.onThinking) {- chatUtils.thinkingManager.start(- 'function',- input.onThinking,- formattedFunctionName,- );- }- }- // If no function name found, continue with current thinking type- }- }- }-- if (jsonObject.function_call) {- // Check for status_message first - highest priority- if (- input.onThinking &&- chatUtils.handleStatusMessage(jsonObject.status_message, input.onThinking)- ) {- // Status message handled, skip function call processing- } else {- // Handle function calls with dynamic thinking messages- const functionName =- jsonObject.function || jsonObject.function_call?.name || 'Unknown';-- const formattedFunctionName = chatUtils.formatFunctionNameForDisplay(functionName);-- // Start function-specific thinking- if (input.onThinking) {- chatUtils.thinkingManager.start(- 'function',- input.onThinking,- formattedFunctionName,- );- }- }- }-- if (jsonObject.content && jsonObject.content !== '') {- // Handle final content transition - only when we're actually getting content- if (messageState === ('debug' as MessageState)) {- handleMessageTransition('final');- }-- // Stop all thinking messages when content starts arriving- chatUtils.thinkingManager.stop();-- // Handle streaming content - append to message- const content = jsonObject.content || '';- if (content) {- // For first content after debug, start fresh message with proper line break- if (messageState === ('final' as MessageState) && message === '') {- message = content;- } else if (messageState === 'initial' && message === '') {- // For content without any thinking (initial state), start fresh- message = content;- } else {- // Append content to existing message for streaming Response- message = message.length > 0 ? `${message}${content}` : content;- }- }-- // INSTANT DISPLAY: Show response immediately with error flags if present- input.onResponse(message, {- isError: jsonObject.isError || false,- errorType: jsonObject.errorType || undefined,- });- }- }-- // Clear accumulated data after processing all JSON objects- // Only clear if we successfully processed some objects- if (jsonObjects.length > 0) {- accumulatedData = '';- }- }- } catch (error) {- if (error.name === 'AbortError') {- input.onResponse('Request was cancelled');- } else {- handleErrorGracefully(error.message);- }- throw error;- } finally {- // Stop all thinking messages when response ends- chatUtils.thinkingManager.stop();- input.onEnd();- }-- return message;- },- extractFirstSentence: (paragraph: string): string => {- const sentenceEndRegex = /([.!?])\s/;- const match = paragraph.match(sentenceEndRegex);- if (match) return paragraph.substring(0, match.index + 1).trim();- return paragraph.trim();- },-};export const createFileFromText = (content: string): IMessageFile => {const timestamp = new Date().toISOString().replace(/[:.]/g, '-');diff --git a/packages/app/src/react/features/ai-chat/utils/scroll-utils.ts b/packages/app/src/react/features/ai-chat/utils/scroll-utils.tsindex a6d42703..fb858cf4 100644--- a/packages/app/src/react/features/ai-chat/utils/scroll-utils.ts+++ b/packages/app/src/react/features/ai-chat/utils/scroll-utils.ts@@ -82,17 +82,6 @@ export class ScrollManager {return distanceFromBottom <= threshold;}- /**- * Check if user is at the very bottom- */- isAtBottom(threshold: number = 10): boolean {- const container = this.getContainer();- if (!container) return true;-- const { scrollTop, scrollHeight, clientHeight } = container;- return scrollHeight - scrollTop <= clientHeight + threshold;- }-/*** Professional scroll to bottom with multiple strategies*/@@ -175,13 +164,6 @@ export class ScrollManager {});}- /**- * Force scroll to bottom (ignores user scroll position)- */- forceScrollToBottom(options: ScrollToBottomOptions = {}): Promise<void> {- return this.scrollToBottom({ ...options, force: true });- }-/*** Force scroll to bottom bypassing cooldown (for user-initiated scrolls)*/@@ -207,59 +189,12 @@ export class ScrollManager {return this.scrollToBottom({ ...options, force: false });}- /**- * Scroll to specific element- */- scrollToElement(element: HTMLElement, options: ScrollOptions = {}): Promise<void> {- return new Promise((resolve) => {- const container = this.getContainer();- if (!container) {- resolve();- return;- }-- const { behavior = 'smooth', block = 'end', inline = 'nearest' } = options;-- element.scrollIntoView({- behavior,- block,- inline,- });-- // Resolve after scroll animation- if (behavior === 'smooth') {- setTimeout(resolve, 300);- } else {- resolve();- }- });- }-- /**- * Check if currently scrolling- */- isCurrentlyScrolling(): boolean {- return this.isScrolling;- }-/*** Reset force scroll cooldown (useful for user-initiated scrolls)*/resetForceScrollCooldown(): void {this.lastForceScrollTime = 0;}-- /**- * Clean up resources- */- destroy(): void {- if (this.scrollTimeout) {- clearTimeout(this.scrollTimeout);- this.scrollTimeout = null;- }- this.scrollContainer = null;- this.isScrolling = false;- }}// Export singleton instance@@ -269,15 +204,8 @@ export const scrollManager = ScrollManager.getInstance();export const scrollToBottom = (options?: ScrollToBottomOptions) =>scrollManager.scrollToBottom(options);-export const forceScrollToBottom = (options?: ScrollToBottomOptions) =>- scrollManager.forceScrollToBottom(options);-export const forceScrollToBottomImmediate = (options?: ScrollToBottomOptions) =>scrollManager.forceScrollToBottomImmediate(options);export const smartScrollToBottom = (options?: ScrollToBottomOptions) =>scrollManager.smartScrollToBottom(options);--export const isNearBottom = (threshold?: number) => scrollManager.isNearBottom(threshold);--export const isAtBottom = (threshold?: number) => scrollManager.isAtBottom(threshold);diff --git a/packages/app/src/react/features/ai-chat/utils/stream.utils.ts b/packages/app/src/react/features/ai-chat/utils/stream.utils.tsindex 6bea308b..50e90fe4 100644--- a/packages/app/src/react/features/ai-chat/utils/stream.utils.ts+++ b/packages/app/src/react/features/ai-chat/utils/stream.utils.ts@@ -286,19 +286,6 @@ export class ThinkingMessageManager {}}- /**- * Updates status message for status type thinking- *- * @param newStatusMessage - New status message- */- updateStatus(newStatusMessage: string): void {- if (this.currentType === 'status' && this.callback) {- const formattedMessage = formatStatusMessage(newStatusMessage);- this.statusMessage = formattedMessage;- this.callback(formattedMessage, 'status');- }- }-/*** Stops thinking messages and clears state*/@@ -314,15 +301,6 @@ export class ThinkingMessageManager {this.callback = null;}- /**- * Gets current thinking type- *- * @returns Current thinking type or null- */- getCurrentType(): TThinkingType | null {- return this.currentType;- }-/*** Gets current message with placeholders replaced*/@@ -365,7 +343,7 @@ export class ThinkingMessageManager {export const processStreamChunk = (chunk: IStreamChunk) => {// When isError is true, the error message is in the content fieldconst errorMessage = chunk.error || (chunk.isError ? chunk.content : null);-+return {hasContent: Boolean(chunk.content && chunk.content.trim() !== ''),hasDebug: Boolean(chunk.debug),