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 Types and Components for Enhanced Type Safety and Clarity

Salman-Ahamed310082825771
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 c7fd79ad..a199fb08 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,14 +4,14 @@
*/
import {
- IAPIConfig,
- IChatError,
- IFileAttachment,
+ TAPIConfig,
+ TChatError,
+ TFileAttachment,
IStreamCallbacks,
- IStreamChunk,
- IStreamConfig,
-} from '@react/features/ai-chat/types/chat.types';
-import { performanceMonitor } from '@react/features/ai-chat/utils/chat-performance-monitor';
+ TStreamChunk,
+ TStreamConfig,
+} from '@react/features/ai-chat/types';
+import { 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';
@@ -19,7 +19,7 @@ import { processStreamChunk, splitJSONStream } from '@src/react/features/ai-chat
/**
* Default configuration for the Chat API Client
*/
-const DEFAULT_CONFIG: IAPIConfig = {
+const DEFAULT_CONFIG: TAPIConfig = {
baseUrl: '/api/page/chat',
defaultHeaders: { 'Content-Type': 'application/json' },
};
@@ -29,7 +29,7 @@ const DEFAULT_CONFIG: IAPIConfig = {
* Handles all communication with the chat service including streaming responses
*/
export class ChatAPIClient {
- private config: IAPIConfig;
+ private config: TAPIConfig;
/**
* Creates a new ChatAPIClient instance
@@ -44,7 +44,7 @@ export class ChatAPIClient {
* });
* ```
*/
- constructor(config: Partial<IAPIConfig> = {}) {
+ constructor(config: Partial<TAPIConfig> = {}) {
this.config = { ...DEFAULT_CONFIG, ...config };
}
@@ -73,7 +73,7 @@ export class ChatAPIClient {
* );
* ```
*/
- async streamChat(streamConfig: IStreamConfig, callbacks: IStreamCallbacks): Promise<void> {
+ async streamChat(streamConfig: TStreamConfig, callbacks: IStreamCallbacks): Promise<void> {
const { agentId, chatId, message, modelId, attachments, signal, headers = {} } = streamConfig;
const { onContent, onMetaMessages, onError, onStart, onComplete } = callbacks;
@@ -85,7 +85,7 @@ export class ChatAPIClient {
// Validate required parameters
// Message can be empty if attachments are provided
if (!agentId || !chatId || (!message && (!attachments || attachments.length === 0))) {
- const error: IChatError = {
+ const error: TChatError = {
message: 'Missing required parameters: agentId, chatId, or message',
type: 'system',
};
@@ -121,7 +121,7 @@ export class ChatAPIClient {
// Handle HTTP errors
if (!response.ok) {
const errorData = await this.parseErrorResponse(response);
- const error: IChatError = {
+ const error: TChatError = {
message: errorData.message || `HTTP ${response.status}: Failed to get response`,
type: 'network',
};
@@ -132,7 +132,7 @@ export class ChatAPIClient {
// Get stream reader
reader = response.body?.getReader();
if (!reader) {
- const error: IChatError = {
+ const error: TChatError = {
message: 'Failed to get response reader - response body is null',
type: 'stream',
};
@@ -240,7 +240,7 @@ export class ChatAPIClient {
* @param callbacks - Event callbacks
*/
private async processChunk(
- chunk: IStreamChunk,
+ chunk: TStreamChunk,
callbacks: Pick<IStreamCallbacks, 'onContent' | 'onMetaMessages'>,
): Promise<void> {
const { onContent, onMetaMessages } = callbacks;
@@ -251,7 +251,7 @@ export class ChatAPIClient {
// Handle errors - throw to stop stream processing, catch block will handle error notification
if (processed.hasError) {
- const error: IChatError = {
+ const error: TChatError = {
type: 'stream',
turnId, // Include turn ID in error
message: processed.error || 'Unknown error occurred',
@@ -279,7 +279,7 @@ export class ChatAPIClient {
* @param signal - Abort signal to check for user cancellation
* @returns Structured chat error
*/
- private handleStreamError(error: unknown, signal: AbortSignal): IChatError {
+ private handleStreamError(error: unknown, signal: AbortSignal): TChatError {
// Check if this is an abort error
if (error instanceof DOMException && error.name === 'AbortError') {
return {
@@ -385,7 +385,7 @@ export class ChatAPIClient {
* // Use attachment.url in chat message
* ```
*/
- async uploadFile(file: File, agentId: string, chatId?: string): Promise<IFileAttachment> {
+ async uploadFile(file: File, agentId: string, chatId?: string): Promise<TFileAttachment> {
const formData = new FormData();
formData.append('file', file);
diff --git a/packages/app/src/react/features/ai-chat/clients/index.ts b/packages/app/src/react/features/ai-chat/clients/index.ts
index 910dc80b..58e1dd34 100644
--- a/packages/app/src/react/features/ai-chat/clients/index.ts
+++ b/packages/app/src/react/features/ai-chat/clients/index.ts
@@ -1,4 +1,4 @@
-import { TUAgentSettings } from '@react/features/ai-chat/types/chat.types';
+import { TAgentSetting } from '@react/features/ai-chat/types';
/**
* Updates agent settings
@@ -16,7 +16,7 @@ import { TUAgentSettings } from '@react/features/ai-chat/types/chat.types';
* });
* ```
*/
-export const updateAgentSettings = async (agentId: string, settings: TUAgentSettings) => {
+export const updateAgentSettings = async (agentId: string, settings: TAgentSetting) => {
const response = await fetch(`/api/page/agent_settings/ai-agent/${agentId}/settings`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
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.tsx
index b6cdaec1..5a0b8bab 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
@@ -8,11 +8,11 @@ import {
UserMessage,
} from '@react/features/ai-chat/components';
import { MESSAGE_TYPES } from '@react/features/ai-chat/constants';
-import { IMessage } from '@react/features/ai-chat/types/chat';
+import { TChatMessage } from '@react/features/ai-chat/types';
import '../../styles/index.css';
-interface IChatProps extends IMessage {
+interface IChatProps extends TChatMessage {
avatar: string;
onRetryClick?: () => void;
scrollToBottom?: () => void;
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 21033e85..c912438b 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
@@ -3,12 +3,12 @@ import {
formatStatusMessage,
} from '@src/react/features/ai-chat/utils/stream';
import { FC, useEffect, useRef, useState } from 'react';
-import { IMetaMessages } from '../../types/chat';
+import { TMetaMessage } from '../../types';
interface IProps {
data: {
avatar?: string;
- metaMessages?: IMetaMessages;
+ metaMessages?: TMetaMessage;
};
scrollToBottom: () => void;
}
diff --git a/packages/app/src/react/features/ai-chat/components/chat/user-message.tsx b/packages/app/src/react/features/ai-chat/components/chat/user-message.tsx
index 46f5dc2a..6871f232 100644
--- a/packages/app/src/react/features/ai-chat/components/chat/user-message.tsx
+++ b/packages/app/src/react/features/ai-chat/components/chat/user-message.tsx
@@ -1,10 +1,10 @@
import { FC } from 'react';
-import { IAttachment } from '../../types/chat';
+import { TAttachment } from '../../types';
import { FileItemPreview } from '../common/FileItemPreview';
interface IProps {
message: string;
- files?: IAttachment[];
+ files?: TAttachment[];
}
export const UserMessage: FC<IProps> = ({ message, files }) => {
diff --git a/packages/app/src/react/features/ai-chat/components/common/FileItemPreview.tsx b/packages/app/src/react/features/ai-chat/components/common/FileItemPreview.tsx
index d428ad35..e43ad90c 100644
--- a/packages/app/src/react/features/ai-chat/components/common/FileItemPreview.tsx
+++ b/packages/app/src/react/features/ai-chat/components/common/FileItemPreview.tsx
@@ -9,7 +9,7 @@ import {
FaRegFileWord,
FaXmark,
} from 'react-icons/fa6';
-import type { IAttachment } from '../../types/chat';
+import type { TAttachment } from '../../types';
const FILE_ICONS: Record<string, ReactElement> = {
pdf: <FaRegFilePdf className="text-white text-xl" />,
@@ -51,7 +51,7 @@ const RemoveButton: FC<IRemoveButtonProps> = memo(({ onRemove }) => (
RemoveButton.displayName = 'RemoveButton';
export interface IFileItemPreviewProps {
- attachment: IAttachment;
+ attachment: TAttachment;
onRemove?: () => void;
isUploading?: boolean;
}
@@ -81,7 +81,7 @@ const isImageType = (mimeType: string): boolean => {
return mimeType.startsWith('image/');
};
-const getPreviewUrl = (attachment: IAttachment): string | null => {
+const getPreviewUrl = (attachment: TAttachment): string | null => {
if (attachment.blobUrl) {
return attachment.blobUrl;
}
diff --git a/packages/app/src/react/features/ai-chat/components/container.tsx b/packages/app/src/react/features/ai-chat/components/container.tsx
index 31f2f3f1..a675caca 100644
--- a/packages/app/src/react/features/ai-chat/components/container.tsx
+++ b/packages/app/src/react/features/ai-chat/components/container.tsx
@@ -1,7 +1,7 @@
-import { IChildren } from '@react/features/ai-chat/types/chat.types';
+import { TChildren } from '@react/features/ai-chat/types';
import { FC, useCallback, useEffect, useRef } from 'react';
-export const Container: FC<IChildren> = ({ children }) => {
+export const Container: FC<TChildren> = ({ children }) => {
const parentElementRef = useRef<HTMLElement | null>(null);
const originalStateRef = useRef<{ className: string; maxWidth: string } | null>(null);
diff --git a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/index.tsx b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/index.tsx
index 290c7542..571f8a77 100644
--- a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/index.tsx
+++ b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/index.tsx
@@ -8,7 +8,8 @@ import { EVENTS } from '@shared/posthog/constants/events';
import { LLMRegistry } from '@shared/services/LLMRegistry.service';
import { llmModelsStore } from '@shared/state_stores/llm-models';
-import { getBadgeFromTags, ILLMModel } from '@react/features/ai-chat/utils';
+import type { TLLMModel } from '@react/features/ai-chat/types';
+import { getBadgeFromTags } from '@react/features/ai-chat/utils';
import { ModelPanel } from './model-panel';
import { ProviderPanel } from './provider-panel';
@@ -22,7 +23,7 @@ interface IProps {
export const ModelDropdown: FC<IProps> = (props) => {
const { currentModel, isModelAgent, isDisabled, onModelChange } = props;
- const [llmModels, setLlmModels] = useState<Array<ILLMModel>>([]);
+ const [llmModels, setLlmModels] = useState<Array<TLLMModel>>([]);
const [isModelsLoading, setIsModelsLoading] = useState<boolean>(true);
const [provider, setProvider] = useState<string>(currentModel);
const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);
@@ -33,7 +34,7 @@ export const ModelDropdown: FC<IProps> = (props) => {
.getState()
.init()
.finally(() => {
- const models: Array<ILLMModel> = LLMRegistry.getSortedModelsByFeatures('tools').map(
+ const models: Array<TLLMModel> = LLMRegistry.getSortedModelsByFeatures('tools').map(
(model) => ({
label: model.label,
value: model.entryId,
diff --git a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/model-panel.tsx b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/model-panel.tsx
index 0d290331..b7fff49f 100644
--- a/packages/app/src/react/features/ai-chat/components/header/model-dropdown/model-panel.tsx
+++ b/packages/app/src/react/features/ai-chat/components/header/model-dropdown/model-panel.tsx
@@ -2,10 +2,11 @@ import { FC } from 'react';
import { cn } from '@react/shared/utils/general';
-import { getBadgeFromTags, ILLMModel } from '@react/features/ai-chat/utils';
+import type { TLLMModel } from '@react/features/ai-chat/types';
+import { getBadgeFromTags } from '@react/features/ai-chat/utils';
interface IProps {
- models: ILLMModel[];
+ models: TLLMModel[];
currentModel: string;
providerIndex: number;
onModelSelect: (model: string) => void; // eslint-disable-line no-unused-vars
diff --git a/packages/app/src/react/features/ai-chat/constants/index.ts b/packages/app/src/react/features/ai-chat/constants/index.ts
index 2244e7c1..5e7cc94b 100644
--- a/packages/app/src/react/features/ai-chat/constants/index.ts
+++ b/packages/app/src/react/features/ai-chat/constants/index.ts
@@ -1,28 +1,19 @@
-import { TMessageType } from '@react/features/ai-chat/types/chat.types';
+import type { TMessageType } from '@react/features/ai-chat/types';
export const CHAT_ACCEPTED_FILE_TYPES = {
- mime: ['*/*'] as const,
- input: '*/*' as const,
+ mime: ['*/*'],
+ input: '*/*',
} as const;
-/** Supported file types for upload - accepts all types */
-export const SUPPORTED_FILE_TYPES = ['*/*'] as const;
-
/** Maximum allowed file size in bytes (5MB) */
export const ALLOWED_FILE_SIZE = 5 * 1024 * 1024;
/** Maximum number of files that can be uploaded at once */
export const MAX_UPLOADS = 5;
-export const CHAT_ERROR_MESSAGE =
- 'An error occurred. If the issue persists, please send message via our feedback channel. [discord.gg/smythos](https://discord.gg/smythos)';
-
-export const USER_STOPPED_MESSAGE = 'Generation interrupted by user';
-
export const DEFAULT_AVATAR_URL =
'https://gravatar.com/avatar/ccd5b19e810febbfd3d4321e27b15f77?s=400&d=mp&r=x';
-// Message types
type TMessageKey = 'USER' | 'SYSTEM' | 'ERROR' | 'DEBUG' | 'META' | 'LOADING';
export const MESSAGE_TYPES: Record<TMessageKey, TMessageType> = {
USER: 'user',
diff --git a/packages/app/src/react/features/ai-chat/contexts/index.tsx b/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsx
similarity index 92%
rename from packages/app/src/react/features/ai-chat/contexts/index.tsx
rename to packages/app/src/react/features/ai-chat/contexts/chat.provider.tsx
index 2238d763..36e7e038 100644
--- a/packages/app/src/react/features/ai-chat/contexts/index.tsx
+++ b/packages/app/src/react/features/ai-chat/contexts/chat.provider.tsx
@@ -1,24 +1,23 @@
import {
useAgentSettings,
+ useChatState,
useCreateChatMutation,
+ useFileUpload,
useScrollToBottom,
useUpdateAgentSettingsMutation,
} from '@react/features/ai-chat/hooks';
-import { useChatState } from '@react/features/ai-chat/hooks/use-chat-state';
-import { useFileUpload } from '@react/features/ai-chat/hooks/use-file-upload';
-import { IChildren } from '@react/features/ai-chat/types/chat.types';
+import type { TChildren } from '@react/features/ai-chat/types';
import { useAgent } from '@react/shared/hooks/agent';
import { Observability } from '@shared/observability';
import { EVENTS } from '@shared/posthog/constants/events';
-import { ChatContext, IChatContext } from '@src/react/features/ai-chat/contexts/chat';
+import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat';
import { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
-export const ChatContextProvider: FC<IChildren> = ({ children }) => {
+export const ChatContextProvider: FC<TChildren> = ({ children }) => {
const params = useParams<{ agentId: string }>();
const agentId = params?.agentId;
- // Direct element refs (chatbot pattern - no useImperativeHandle needed)
const inputRef = useRef<HTMLTextAreaElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
@@ -188,3 +187,4 @@ export const ChatContextProvider: FC<IChildren> = ({ children }) => {
return <ChatContext.Provider value={values}>{children}</ChatContext.Provider>;
};
+
diff --git a/packages/app/src/react/features/ai-chat/contexts/chat.tsx b/packages/app/src/react/features/ai-chat/contexts/chat.ts
similarity index 86%
rename from packages/app/src/react/features/ai-chat/contexts/chat.tsx
rename to packages/app/src/react/features/ai-chat/contexts/chat.ts
index 8cc6a5fd..f8ae35ae 100644
--- a/packages/app/src/react/features/ai-chat/contexts/chat.tsx
+++ b/packages/app/src/react/features/ai-chat/contexts/chat.ts
@@ -1,6 +1,5 @@
-/* eslint-disable no-unused-vars */
-import { IFileUpload, IMessage } from '@react/features/ai-chat/types/chat';
-import { AgentDetails, AgentSettings } from '@react/shared/types/agent-data.types';
+import type { IFileUpload, TChatMessage } from '@react/features/ai-chat/types';
+import type { AgentDetails, AgentSettings } from '@react/shared/types/agent-data.types';
import { createContext, RefObject } from 'react';
export interface IChatContext {
@@ -18,7 +17,7 @@ export interface IChatContext {
files: IFileUpload;
chat: {
isChatCreating: boolean;
- messages: IMessage[];
+ messages: TChatMessage[];
isStreaming: boolean;
sendMessage: (message: string) => Promise<void>;
retryMessage: () => void;
@@ -31,7 +30,6 @@ export interface IChatContext {
scrollToBottom: (smooth?: boolean) => void;
smartScrollToBottom: (smooth?: boolean) => void;
};
- // Model override (temporary, not saved to agent config)
modelOverride: string | null;
setModelOverride: (model: string | null) => void;
}
@@ -67,3 +65,4 @@ export const ChatContext = createContext<IChatContext>({
modelOverride: null,
setModelOverride: () => {},
});
+
diff --git a/packages/app/src/react/features/ai-chat/contexts/index.ts b/packages/app/src/react/features/ai-chat/contexts/index.ts
new file mode 100644
index 00000000..3e12aa78
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/contexts/index.ts
@@ -0,0 +1,3 @@
+export * from './chat';
+export * from './chat.provider';
+
diff --git a/packages/app/src/react/features/ai-chat/hooks/index.ts b/packages/app/src/react/features/ai-chat/hooks/index.ts
index 1235c2f1..f8fb627d 100644
--- a/packages/app/src/react/features/ai-chat/hooks/index.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/index.ts
@@ -1,6 +1,8 @@
export * from './use-agent-settings';
export * from './use-chat-mutation';
+export * from './use-chat-state';
export * from './use-clipboard-paste';
export * from './use-drag-and-drop';
+export * from './use-file-upload';
export * from './use-scroll';
export * from './use-store';
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-agent-settings.ts b/packages/app/src/react/features/ai-chat/hooks/use-agent-settings.ts
index b0d58998..2f005487 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-agent-settings.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-agent-settings.ts
@@ -1,7 +1,7 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { updateAgentSettings } from '@react/features/ai-chat/clients';
-import { TUAgentSettings } from '@react/features/ai-chat/types/chat.types';
+import { TAgentSetting } from '@react/features/ai-chat/types';
import { AgentSettings } from '@react/shared/types/agent-data.types';
export const useAgentSettings = (agentId: string) => {
@@ -32,7 +32,7 @@ export const useUpdateAgentSettingsMutation = () => {
const queryClient = useQueryClient();
return useMutation(
- (params: { agentId: string; settings: TUAgentSettings }) =>
+ (params: { agentId: string; settings: TAgentSetting }) =>
updateAgentSettings(params.agentId, params.settings),
{
onSuccess: (_, variables) => {
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts
index 0c559760..d82da5aa 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat-state.ts
@@ -1,19 +1,19 @@
import { ChatAPIClient } from '@react/features/ai-chat/clients/chat-api.client';
import { MESSAGE_TYPES } from '@react/features/ai-chat/constants';
import type {
- IAttachment,
- IChatError,
+ TAttachment,
+ TChatError,
IChatState,
- IConfigOptions,
- IMessage,
- IMetaMessages,
-} from '@react/features/ai-chat/types/chat';
+ TChatStateConfig,
+ TChatMessage,
+ TMetaMessage,
+} from '@react/features/ai-chat/types';
import { useCallback, useMemo, useRef, useState } from 'react';
-export const useChatState = (options: IConfigOptions): IChatState => {
+export const useChatState = (options: TChatStateConfig): IChatState => {
const { agentId, chatId, modelId, enableMetaMessages = false, inputRef } = options;
- const [messages, setMessages] = useState<IMessage[]>([]);
+ const [messages, setMessages] = useState<TChatMessage[]>([]);
const [isStreaming, setIsStreaming] = useState<boolean>(false);
const abortRef = useRef<AbortController | null>(null);
@@ -60,7 +60,7 @@ export const useChatState = (options: IConfigOptions): IChatState => {
return updated;
}
- const newMessage: IMessage = {
+ const newMessage: TChatMessage = {
id: Date.now() + Math.random(),
type: MESSAGE_TYPES.SYSTEM,
content: content,
@@ -72,7 +72,7 @@ export const useChatState = (options: IConfigOptions): IChatState => {
}, []);
const onMetaMessage = useCallback(
- (meta: IMetaMessages): void => {
+ (meta: TMetaMessage): void => {
if (!enableMetaMessages) return;
setMessages((prev) => {
@@ -156,7 +156,7 @@ export const useChatState = (options: IConfigOptions): IChatState => {
}
// Create new META message
- const newMessage: IMessage = {
+ const newMessage: TChatMessage = {
id: Date.now() + Math.random(),
type: MESSAGE_TYPES.META,
content: debugText,
@@ -170,7 +170,7 @@ export const useChatState = (options: IConfigOptions): IChatState => {
[enableMetaMessages],
);
- const onStreamError = useCallback((error: IChatError): void => {
+ const onStreamError = useCallback((error: TChatError): void => {
if (error.isAborted) {
setIsStreaming(false);
return;
@@ -178,7 +178,7 @@ export const useChatState = (options: IConfigOptions): IChatState => {
setMessages((prev) => {
const filtered = prev.filter((msg) => msg.type !== MESSAGE_TYPES.LOADING);
- const errorMessage: IMessage = {
+ const errorMessage: TChatMessage = {
id: Date.now() + Math.random(),
type: MESSAGE_TYPES.ERROR,
content: error.message || 'An error occurred',
@@ -193,7 +193,7 @@ export const useChatState = (options: IConfigOptions): IChatState => {
const sendMessage = useCallback(
async (
message: string,
- currentAttachments: IAttachment[] = [],
+ currentAttachments: TAttachment[] = [],
shouldSetUserMessage = true,
): Promise<void> => {
if (isStreaming) return;
@@ -206,7 +206,7 @@ export const useChatState = (options: IConfigOptions): IChatState => {
setMessages((prev) => {
const msgCount = prev.length;
- const userMessage: IMessage | null = shouldSetUserMessage
+ const userMessage: TChatMessage | null = shouldSetUserMessage
? {
id: msgCount + 1,
type: MESSAGE_TYPES.USER,
@@ -226,7 +226,7 @@ export const useChatState = (options: IConfigOptions): IChatState => {
}
: null;
- const loadingMessage: IMessage = {
+ const loadingMessage: TChatMessage = {
id: shouldSetUserMessage ? msgCount + 2 : msgCount + 1,
type: MESSAGE_TYPES.LOADING,
content: '',
@@ -319,7 +319,7 @@ export const useChatState = (options: IConfigOptions): IChatState => {
return msg;
});
- const errorMessage: IMessage = {
+ const errorMessage: TChatMessage = {
id: Date.now() + Math.random(),
type: MESSAGE_TYPES.ERROR,
content: 'Generation interrupted by user',
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-clipboard-paste.ts b/packages/app/src/react/features/ai-chat/hooks/use-clipboard-paste.ts
index e0a8ba5a..556bf423 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-clipboard-paste.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-clipboard-paste.ts
@@ -1,13 +1,12 @@
-/* eslint-disable no-unused-vars */
import { RefObject, useCallback, useEffect } from 'react';
-interface UseClipboardPasteOptions {
+type TClipboardPasteConfig = {
onFilePaste: (files: File[]) => void;
enabled?: boolean;
targetRef?: RefObject<HTMLTextAreaElement | HTMLElement>;
largeTextThreshold?: number;
onLargeTextPaste?: (text: string) => void;
-}
+};
/**
* Custom hook to handle clipboard paste events for files, images, and large text
@@ -53,7 +52,7 @@ export const useClipboardPaste = ({
targetRef,
largeTextThreshold,
onLargeTextPaste,
-}: UseClipboardPasteOptions) => {
+}: TClipboardPasteConfig) => {
const handlePaste = useCallback(
(event: ClipboardEvent) => {
if (!event.clipboardData) return;
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-drag-and-drop.ts b/packages/app/src/react/features/ai-chat/hooks/use-drag-and-drop.ts
index e8ec22f9..00c2cfe2 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-drag-and-drop.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-drag-and-drop.ts
@@ -1,8 +1,10 @@
import { RefObject, useCallback, useEffect, useRef } from 'react';
-type IProps = { onDrop: (files: File[]) => Promise<void> }; // eslint-disable-line no-unused-vars
+type TDragAndDropConfig = {
+ onDrop: (files: File[]) => Promise<void>;
+};
-export const useDragAndDrop = ({ onDrop }: IProps): RefObject<HTMLElement> => {
+export const useDragAndDrop = ({ onDrop }: TDragAndDropConfig): RefObject<HTMLElement> => {
const containerRef = useRef<HTMLElement>(null);
const dragCounterRef = useRef(0);
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-file-upload.ts b/packages/app/src/react/features/ai-chat/hooks/use-file-upload.ts
index 8edf3f49..e4ac3f48 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,26 +1,26 @@
import { ALLOWED_FILE_SIZE, MAX_UPLOADS } from '@react/features/ai-chat/constants';
import type {
- IFileAttachment,
+ TFileAttachment,
IFileUpload,
- IUploadStatus,
-} from '@react/features/ai-chat/types/chat';
+ TUploadStatus,
+} from '@react/features/ai-chat/types';
import {
generateUniqueFileId,
uploadFiles,
validateSingleFile,
-} from '@react/features/ai-chat/utils/file';
+} from '@react/features/ai-chat/utils';
import { useCallback, useEffect, useRef, useState } from 'react';
-type IProps = {
+type TFileUploadConfig = {
agentId?: string;
chatId?: string;
};
-export const useFileUpload = (options: IProps): IFileUpload => {
+export const useFileUpload = (options: TFileUploadConfig): IFileUpload => {
const { agentId, chatId } = options;
- const [attachments, setAttachments] = useState<IFileAttachment[]>([]);
- const [status, setStatus] = useState<Record<string, IUploadStatus>>({});
+ const [attachments, setAttachments] = useState<TFileAttachment[]>([]);
+ const [status, setStatus] = useState<Record<string, TUploadStatus>>({});
const [uploading, setUploading] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
@@ -85,7 +85,7 @@ export const useFileUpload = (options: IProps): IFileUpload => {
if (valid.length > 0) {
const pending = valid.slice(0, slots);
- const created: IFileAttachment[] = pending.map(({ file, id }) => {
+ const created: TFileAttachment[] = 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/hooks/use-scroll.ts b/packages/app/src/react/features/ai-chat/hooks/use-scroll.ts
index 1d8daa25..f4820d63 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 '@src/react/features/ai-chat/utils/scroll';
+import { scrollManager } from '@react/features/ai-chat/utils';
export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {
const [showScrollButton, setShowScrollButton] = useState(false);
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.ts
similarity index 78%
rename from packages/app/src/react/features/ai-chat/hooks/use-store.tsx
rename to packages/app/src/react/features/ai-chat/hooks/use-store.ts
index f745b7bf..80347f5c 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-store.tsx
+++ b/packages/app/src/react/features/ai-chat/hooks/use-store.ts
@@ -1,4 +1,4 @@
-import { ChatContext, IChatContext } from '@src/react/features/ai-chat/contexts/chat';
+import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat';
import { useContext } from 'react';
export const useChatStores = () => useContext(ChatContext);
@@ -8,3 +8,4 @@ export const useChatStore = <T extends keyof IChatContext>(state: T): IChatConte
if (!store) throw new Error('ChatContext not found');
return store[state];
};
+
diff --git a/packages/app/src/react/features/ai-chat/types/agent.ts b/packages/app/src/react/features/ai-chat/types/agent.ts
new file mode 100644
index 00000000..1b53e71c
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/agent.ts
@@ -0,0 +1,2 @@
+export type TAgentSetting = { key: string; value: string };
+
diff --git a/packages/app/src/react/features/ai-chat/types/chat.ts b/packages/app/src/react/features/ai-chat/types/chat.ts
deleted file mode 100644
index 6204db30..00000000
--- a/packages/app/src/react/features/ai-chat/types/chat.ts
+++ /dev/null
@@ -1,186 +0,0 @@
-/* eslint-disable no-unused-vars */
-import type { Dispatch, RefObject, SetStateAction } from 'react';
-
-// ============================================================================
-// MESSAGE TYPES
-// ============================================================================
-
-export type TMessageType = 'user' | 'system' | 'debug' | 'error' | 'loading' | 'meta';
-
-export interface IFunctionCall {
- name?: string;
- topic?: string;
- arguments?: Record<string, unknown>;
-}
-
-export interface IMetaMessages {
- hashId?: string;
- debugOn?: boolean;
- debug?: string;
- title?: string;
- statusMessage?: string;
- function?: string;
- callParams?: unknown;
- parameters?: unknown;
- functionCall?: IFunctionCall;
-}
-
-export interface IAttachment {
- name: string;
- type: string;
- size: number;
- url?: string;
- blobUrl?: string | null;
- file?: File;
-}
-
-export interface IMessage {
- id: number;
- type: TMessageType;
- content: string;
- metaMessages?: IMetaMessages;
- updatedAt?: number;
- attachments?: IAttachment[];
-}
-
-// ============================================================================
-// FILE & ATTACHMENT TYPES
-// ============================================================================
-
-export interface IMessageFile {
- id: string;
- file: File;
- url?: string;
- name?: string;
- type?: string;
- size?: number;
- metadata: {
- key?: string;
- fileType?: string;
- publicUrl?: string;
- previewUrl?: string;
- isUploading?: boolean;
- };
-}
-
-export interface IFileAttachment {
- id: string;
- file: File;
- blobUrl: string | null;
- name: string;
- type: string;
- size: number;
- url?: string;
-}
-
-export interface IUploadStatus {
- status: 'uploading' | 'completed' | 'error';
- progress: number;
-}
-
-// ============================================================================
-// STREAMING & API TYPES
-// ============================================================================
-
-export interface IStreamChunk {
- conversationTurnId?: string;
- content?: string;
- debugOn?: boolean;
- title?: string;
- debug?: string;
- status_message?: string;
- callParams?: string;
- parameters?: Record<string, unknown>;
- function?: string;
- function_call?: IFunctionCall;
- hashId?: string;
- error?: string;
- isError?: boolean;
-}
-
-export interface IStreamConfig {
- agentId: string;
- chatId: string;
- domain?: string;
- port?: number;
- message: string;
- modelId?: string;
- attachments?: IMessageFile[];
- enableMetaMessages?: boolean;
- signal: AbortSignal;
- headers?: Record<string, string>;
-}
-
-export interface IStreamCallbacks {
- onContent: (content: string, turnId?: string) => void;
- onMetaMessages?: (metaMessages: IMetaMessages, turnId?: string) => void;
- onError: (error: IChatError) => void;
- onStart?: () => void;
- onComplete: () => void;
-}
-
-export type TErrorType = 'stream' | 'network' | 'abort' | 'system';
-
-export interface IChatError {
- message: string;
- type: TErrorType;
- turnId?: string;
- originalError?: Error | unknown;
- isAborted?: boolean;
-}
-
-export interface IAPIConfig {
- domain?: string;
- port?: number;
- baseUrl?: string;
- defaultHeaders?: Record<string, string>;
- timeout?: number;
- retry?: { attempts: number; delay: number };
-}
-
-// ============================================================================
-// HOOK RETURN TYPES
-// ============================================================================
-
-/**
- * Interface for focusable input elements
- * Used for auto-focus functionality after stream completion
- */
-export interface IFocusableInput {
- focus: () => void;
-}
-
-export interface IConfigOptions {
- agentId: string;
- chatId: string;
- modelId?: string;
- enableMetaMessages?: boolean;
-
- /** Optional ref to input element for auto-focus on stream complete */
- inputRef?: RefObject<IFocusableInput | null>;
-}
-
-export interface IChatState {
- messages: IMessage[];
- setMessages: Dispatch<SetStateAction<IMessage[]>>;
- isStreaming: boolean;
- setIsStreaming: Dispatch<SetStateAction<boolean>>;
- sendMessage: (
- message: string,
- currentAttachments?: IAttachment[],
- shouldSetUserMessage?: boolean,
- ) => Promise<void>;
- stopStreaming: () => void;
- retryLastMessage: () => void;
-}
-
-export interface IFileUpload {
- attachments: IFileAttachment[];
- status: Record<string, IUploadStatus>;
- uploading: boolean;
- errorMessage: string;
- addFiles: (files: File[]) => Promise<void>;
- remove: (index: number) => void;
- clear: (preserveBlobUrls?: boolean) => void;
- clearError: () => void;
-}
diff --git a/packages/app/src/react/features/ai-chat/types/chat.types.ts b/packages/app/src/react/features/ai-chat/types/chat.types.ts
deleted file mode 100644
index a5ed554e..00000000
--- a/packages/app/src/react/features/ai-chat/types/chat.types.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-// ============================================================================
-// CORE MESSAGE TYPES
-// ============================================================================
-
-export type IChildren = { children: React.ReactNode };
-
-/**
- * Message type discriminator
- * Complete state representation through type alone
- *
- * - 'user': Message from user
- * - 'system': Response from AI/system
- * - 'debug': AI is processing/thinking
- * - 'loading': AI is generating response (replying/retrying)
- * - 'error': Error occurred during processing
- */
-export type TMessageType = 'user' | 'system' | 'debug' | 'loading' | 'error' | 'meta';
-
-/**
- * File attachment structure
- * Simplified from previous complex nested structure
- */
-export interface IMessageFile {
- id: string; // Required ID for React keys and tracking
- file: File; // The actual File object
- url?: string; // Public URL (stored after upload)
- name?: string; // File name (stored after upload)
- type?: string; // File type/MIME type (stored after upload)
- size?: number; // File size in bytes (stored after upload)
- metadata: {
- key?: string;
- fileType?: string;
- publicUrl?: string;
- previewUrl?: string;
- isUploading?: boolean;
- };
-}
-
-// ============================================================================
-// AGENT SETTINGS TYPES
-// ============================================================================
-
-export type TUAgentSettings = { key: string; value: string };
-
-// ============================================================================
-// STREAMING TYPES
-// ============================================================================
-
-export interface IFunctionCall {
- name?: string;
- arguments?: Record<string, unknown>;
- topic?: string;
-}
-
-export interface IMetaMessages {
- debug: string;
- title: string;
- statusMessage: string;
- function: string;
- callParams: string;
- parameters: Record<string, unknown>;
- functionCall: IFunctionCall;
-}
-
-/**
- * Stream chunk from backend
- * Only includes actually used properties
- */
-export interface IStreamChunk {
- conversationTurnId?: string; // Conversation Turn ID
- content?: string; // Content chunk for streaming responses
- debugOn?: boolean; // Debug session indicator
- title?: string; // Title of the message
- debug?: string; // Debug information
- status_message?: string; // Status/thinking message
- callParams?: string; // Call parameters
- parameters?: Record<string, unknown>; // Parameters
- function?: string; // Function/tool name
- function_call?: IFunctionCall; // Function call information
- hashId?: string; // Debug tracking hash
- error?: string; // Error message
- isError?: boolean; // Error indicator
-}
-
-export type TThinkingType = 'tools' | 'general'; // Thinking message type discriminator
-
-export interface IStreamConfig {
- agentId: string; // Target agent ID
- chatId: string; // Conversation ID
- message: string; // User message content
- modelId?: string; // Model ID to override backend model selection
- attachments?: IMessageFile[]; // File attachments
- signal: AbortSignal; // Abort signal for cancellation
- headers?: Record<string, string>; // Custom headers
-}
-
-export interface IFileAttachment {
- url: string; // Public URL
- name?: string; // Filename
- type?: string; // MIME type
- size?: number; // File size
-}
-
-/**
- * Stream event callbacks
- */
-/* eslint-disable no-unused-vars */
-export interface IStreamCallbacks {
- onContent: (content: string, turnId?: string) => void;
- onMetaMessages?: (metaMessages: IMetaMessages, turnId?: string) => void;
- onError: (error: IChatError) => void; // Error occurred - error object now includes turnId
- onStart?: () => void; // Stream started
- onComplete: () => void; // Stream completed
-}
-
-// ============================================================================
-// ERROR TYPES
-// ============================================================================
-
-export type TErrorType = 'stream' | 'network' | 'abort' | 'system';
-
-export interface IChatError {
- message: string; // Error message
- type: TErrorType; // Error type
- turnId?: string; // Conversation turn ID for grouping
- originalError?: Error | unknown; // Original error object
- isAborted?: boolean; // User-initiated abort flag
-}
-
-// ============================================================================
-// API CLIENT TYPES
-// ============================================================================
-
-/**
- * API client configuration
- */
-export interface IAPIConfig {
- baseUrl?: string; // Base API URL
- defaultHeaders?: Record<string, string>; // Default headers
- timeout?: number; // Request timeout
- retry?: { attempts: number; delay: number }; // Retry configuration
-}
diff --git a/packages/app/src/react/features/ai-chat/types/common.ts b/packages/app/src/react/features/ai-chat/types/common.ts
new file mode 100644
index 00000000..b5b8a23c
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/common.ts
@@ -0,0 +1,2 @@
+export type TChildren = { children: React.ReactNode };
+
diff --git a/packages/app/src/react/features/ai-chat/types/file.ts b/packages/app/src/react/features/ai-chat/types/file.ts
new file mode 100644
index 00000000..ea1193ca
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/file.ts
@@ -0,0 +1,31 @@
+export type TUploadFile = {
+ id: string;
+ file: File;
+ url?: string;
+ name?: string;
+ type?: string;
+ size?: number;
+ metadata: {
+ key?: string;
+ fileType?: string;
+ publicUrl?: string;
+ previewUrl?: string;
+ isUploading?: boolean;
+ };
+};
+
+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.ts
new file mode 100644
index 00000000..b2c44b6a
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/hooks.ts
@@ -0,0 +1,41 @@
+import type { Dispatch, RefObject, SetStateAction } from 'react';
+import type { TAttachment, TChatMessage } from './message';
+import type { TFileAttachment, TUploadStatus } from './file';
+
+export interface IFocusable {
+ focus: () => void;
+}
+
+export type TChatStateConfig = {
+ agentId: string;
+ chatId: string;
+ modelId?: string;
+ enableMetaMessages?: boolean;
+ inputRef?: RefObject<IFocusable | null>;
+};
+
+export interface IChatState {
+ messages: TChatMessage[];
+ setMessages: Dispatch<SetStateAction<TChatMessage[]>>;
+ isStreaming: boolean;
+ setIsStreaming: Dispatch<SetStateAction<boolean>>;
+ sendMessage: (
+ message: string,
+ currentAttachments?: TAttachment[],
+ shouldSetUserMessage?: boolean,
+ ) => Promise<void>;
+ stopStreaming: () => void;
+ retryLastMessage: () => void;
+}
+
+export interface IFileUpload {
+ attachments: TFileAttachment[];
+ status: Record<string, TUploadStatus>;
+ uploading: boolean;
+ errorMessage: string;
+ addFiles: (files: File[]) => Promise<void>;
+ remove: (index: number) => void;
+ clear: (preserveBlobUrls?: boolean) => void;
+ clearError: () => void;
+}
+
diff --git a/packages/app/src/react/features/ai-chat/types/index.ts b/packages/app/src/react/features/ai-chat/types/index.ts
new file mode 100644
index 00000000..c86496e5
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/index.ts
@@ -0,0 +1,8 @@
+export * from './agent';
+export * from './common';
+export * from './file';
+export * from './hooks';
+export * from './message';
+export * from './model';
+export * from './performance';
+export * from './stream';
diff --git a/packages/app/src/react/features/ai-chat/types/message.ts b/packages/app/src/react/features/ai-chat/types/message.ts
new file mode 100644
index 00000000..f47ae2c0
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/message.ts
@@ -0,0 +1,40 @@
+export type TMessageType = 'user' | 'system' | 'debug' | 'error' | 'loading' | 'meta';
+
+export type TThinkingType = 'tools' | 'general';
+
+export type TFunctionCall = {
+ name?: string;
+ topic?: string;
+ arguments?: Record<string, unknown>;
+};
+
+export type TMetaMessage = {
+ hashId?: string;
+ debugOn?: boolean;
+ debug?: string;
+ title?: string;
+ statusMessage?: string;
+ function?: string;
+ callParams?: unknown;
+ parameters?: unknown;
+ functionCall?: TFunctionCall;
+};
+
+export type TAttachment = {
+ name: string;
+ type: string;
+ size: number;
+ url?: string;
+ blobUrl?: string | null;
+ file?: File;
+};
+
+export type TChatMessage = {
+ id: number;
+ type: TMessageType;
+ content: string;
+ metaMessages?: TMetaMessage;
+ updatedAt?: number;
+ attachments?: TAttachment[];
+};
+
diff --git a/packages/app/src/react/features/ai-chat/types/model.ts b/packages/app/src/react/features/ai-chat/types/model.ts
new file mode 100644
index 00000000..f5df5acd
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/model.ts
@@ -0,0 +1,8 @@
+export type TLLMModel = {
+ label: string;
+ value: string;
+ tags: string[];
+ default?: boolean;
+ provider: string;
+};
+
diff --git a/packages/app/src/react/features/ai-chat/types/performance.ts b/packages/app/src/react/features/ai-chat/types/performance.ts
new file mode 100644
index 00000000..ea94c4f6
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/performance.ts
@@ -0,0 +1,57 @@
+/**
+ * Represents a single chunk's performance metrics
+ */
+export type TChunkMetric = {
+ /** High-resolution timestamp when chunk was received */
+ timestamp: number;
+ /** Sequential index of this chunk in the stream */
+ chunkIndex: number;
+ /** Time elapsed since previous chunk (milliseconds) */
+ networkTime?: number;
+ /** Time spent processing/parsing the chunk (milliseconds) */
+ processingTime?: number;
+ /** Size of chunk data in bytes */
+ chunkSize: number;
+ /** Type of content in this chunk */
+ type: 'content' | 'thinking' | 'tool' | 'debug';
+};
+
+/**
+ * Aggregated performance metrics for an entire stream
+ */
+export type TPerformanceMetrics = {
+ /** Total number of chunks received */
+ totalChunks: number;
+ /** Average time between chunks (milliseconds) */
+ averageNetworkTime: number;
+ /** Average processing time per chunk (milliseconds) */
+ averageProcessingTime: number;
+ /** Total stream duration (milliseconds) */
+ totalDuration: number;
+ /** Chunk with highest total latency */
+ slowestChunk: TChunkMetric | null;
+ /** Throughput in chunks per second */
+ chunksPerSecond: number;
+};
+
+/**
+ * Global debug interface exposed on window object
+ */
+export interface IChatDebugInterface {
+ /** Enable performance monitoring */
+ enable: () => void;
+ /** Disable performance monitoring */
+ disable: () => void;
+ /** Get current performance metrics */
+ metrics: () => TPerformanceMetrics;
+}
+
+/**
+ * Extend Window interface with chatDebug property
+ */
+declare global {
+ interface Window {
+ chatDebug: IChatDebugInterface;
+ }
+}
+
diff --git a/packages/app/src/react/features/ai-chat/types/stream.ts b/packages/app/src/react/features/ai-chat/types/stream.ts
new file mode 100644
index 00000000..b77dca90
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/types/stream.ts
@@ -0,0 +1,59 @@
+import type { TFunctionCall, TMetaMessage } from './message';
+import type { TUploadFile } from './file';
+
+export type TStreamChunk = {
+ conversationTurnId?: string;
+ content?: string;
+ debugOn?: boolean;
+ title?: string;
+ debug?: string;
+ status_message?: string;
+ callParams?: string;
+ parameters?: Record<string, unknown>;
+ function?: string;
+ function_call?: TFunctionCall;
+ hashId?: string;
+ error?: string;
+ isError?: boolean;
+};
+
+export type TStreamConfig = {
+ agentId: string;
+ chatId: string;
+ domain?: string;
+ port?: number;
+ message: string;
+ modelId?: string;
+ attachments?: TUploadFile[];
+ enableMetaMessages?: boolean;
+ signal: AbortSignal;
+ headers?: Record<string, string>;
+};
+
+export interface IStreamCallbacks {
+ onContent: (content: string, turnId?: string) => void;
+ onMetaMessages?: (metaMessages: TMetaMessage, turnId?: string) => void;
+ onError: (error: TChatError) => void;
+ onStart?: () => void;
+ onComplete: () => void;
+}
+
+export type TErrorType = 'stream' | 'network' | 'abort' | 'system';
+
+export type TChatError = {
+ message: string;
+ type: TErrorType;
+ turnId?: string;
+ originalError?: Error | unknown;
+ isAborted?: boolean;
+};
+
+export type TAPIConfig = {
+ domain?: string;
+ port?: number;
+ baseUrl?: string;
+ defaultHeaders?: Record<string, string>;
+ timeout?: number;
+ retry?: { attempts: number; delay: number };
+};
+
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 46699ebe..e476f979 100644
--- a/packages/app/src/react/features/ai-chat/utils/file.ts
+++ b/packages/app/src/react/features/ai-chat/utils/file.ts
@@ -1,111 +1,17 @@
-/**
- * Constants for file upload limitations
- */
-export const FILE_LIMITS = {
- MAX_FILE_SIZE: 5 * 1024 * 1024, // 5MB in bytes
- MAX_ATTACHED_FILES: 5,
- ACCEPTED_TYPES: ['*/*'], // Accept all file types like chatbot
-} as const;
-
-/**
- * Validates a single file against size constraints only
- * @param file - The file to validate
- * @returns An error message if validation fails, null if validation passes
- */
-export const validateSingleFile = (file: File): string | null => {
- if (file.size > FILE_LIMITS.MAX_FILE_SIZE) {
- return 'File size exceeds 5MB limit';
- }
-
- return null;
-};
-
-/**
- * Generates a unique ID for a file
- * @param file - The file to generate ID for
- * @returns Unique file identifier string
- */
-export const generateUniqueFileId = (file: File): string => {
- return `${file.name}-${file.size}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
-};
-
-/**
- * Interface for upload files props
- */
-interface IUploadFilesProps {
- files: File[];
- agentId?: string;
- chatId?: string;
-}
-
-/**
- * Interface for upload response
- */
-interface IUploadResponse {
- files?: Array<{
- url: string;
- name?: string;
- type?: string;
- size?: number;
- mimetype?: string;
- }>;
-}
+import type { TUploadFile } from '@react/features/ai-chat/types';
/**
- * Uploads files to the server
- * @param props - Upload configuration
- * @returns Promise with upload response containing file URLs
+ * 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 uploadFiles = async (props: IUploadFilesProps): Promise<IUploadResponse> => {
- const { files, agentId, chatId } = props;
-
- try {
- const formData = new FormData();
- files.forEach((file) => {
- formData.append('file', file);
- });
-
- const headers: Record<string, string> = {};
-
- if (agentId) {
- headers['X-AGENT-ID'] = agentId;
- }
- if (chatId) {
- headers['x-conversation-id'] = chatId;
- }
-
- const response = await fetch('/api/page/chat/upload', {
- method: 'POST',
- headers,
- body: formData,
- });
-
- if (!response.ok) {
- throw new Error(`Upload failed: ${response.statusText}`);
- }
-
- const data = await response.json();
- 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;
- }) => ({
- url: f.url || f.publicUrl || '',
- name: f.name,
- type: f.mimetype || f.type,
- size: f.size,
- }),
- ),
- };
- } catch (error) {
- console.error('Error uploading files:', error); // eslint-disable-line no-console
- throw error;
- }
+export const createFileFromText = (content: string): TUploadFile => {
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
+ const name = `text-${timestamp}.txt`;
+ const blob = new Blob([content], { type: 'text/plain' });
+ const file = new File([blob], name, { type: 'text/plain' });
+ const id = `text-${timestamp}`;
+
+ return { file, metadata: { fileType: 'text/plain', isUploading: false }, id };
};
diff --git a/packages/app/src/react/features/ai-chat/utils/index.ts b/packages/app/src/react/features/ai-chat/utils/index.ts
index ae3ee3fb..e62fd902 100644
--- a/packages/app/src/react/features/ai-chat/utils/index.ts
+++ b/packages/app/src/react/features/ai-chat/utils/index.ts
@@ -1,61 +1,6 @@
-import { IMessageFile } from '@react/features/ai-chat/types/chat.types';
-
-/** 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,
-): void => {
- if (!textarea) return;
-
- textarea.style.height = 'auto';
- const newHeight = Math.min(textarea.scrollHeight, maxHeight);
- textarea.style.height = `${newHeight}px`;
- textarea.style.overflowY = newHeight === maxHeight ? 'auto' : 'hidden';
-};
-
-export const createFileFromText = (content: string): IMessageFile => {
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
- const name = `text-${timestamp}.txt`;
- const blob = new Blob([content], { type: 'text/plain' });
- const file = new File([blob], name, { type: 'text/plain' });
- const id = `text-${timestamp}`;
-
- return { file, metadata: { fileType: 'text/plain', isUploading: false }, id };
-};
-
-/**
- * LLM Model configuration interface
- */
-export interface ILLMModel {
- label: string;
- value: string;
- tags: string[];
- default?: boolean;
- provider: string;
-}
-
-/**
- * Badge configuration for model tags (enterprise, smythos, personal, limited)
- */
-const BADGE_TAGS: Record<string, boolean> = {
- enterprise: true,
- smythos: true,
- personal: true,
- limited: true,
-};
-
-/**
- * Extracts display badge from model tags
- * @param tags - Array of model tags
- * @returns Badge string for display
- */
-export function getBadgeFromTags(tags: string[]): string {
- return tags.filter((tag) => BADGE_TAGS[tag?.toLowerCase()]).join(' ');
-}
+export * from './file';
+export * from './model';
+export * from './performance-monitor';
+export * from './scroll';
+export * from './stream';
+export * from './textarea';
diff --git a/packages/app/src/react/features/ai-chat/utils/model.ts b/packages/app/src/react/features/ai-chat/utils/model.ts
new file mode 100644
index 00000000..b077d84a
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/utils/model.ts
@@ -0,0 +1,18 @@
+/**
+ * Badge configuration for model tags (enterprise, smythos, personal, limited)
+ */
+const BADGE_TAGS: Record<string, boolean> = {
+ enterprise: true,
+ smythos: true,
+ personal: true,
+ 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/chat-performance-monitor.ts b/packages/app/src/react/features/ai-chat/utils/performance-monitor.ts
similarity index 73%
rename from packages/app/src/react/features/ai-chat/utils/chat-performance-monitor.ts
rename to packages/app/src/react/features/ai-chat/utils/performance-monitor.ts
index c990dc9f..658cb601 100644
--- a/packages/app/src/react/features/ai-chat/utils/chat-performance-monitor.ts
+++ b/packages/app/src/react/features/ai-chat/utils/performance-monitor.ts
@@ -26,47 +26,7 @@
* console.log(metrics);
*/
-/**
- * Represents a single chunk's performance metrics
- */
-interface ChunkMetric {
- timestamp: number; // High-resolution timestamp when chunk was received
- chunkIndex: number; // Sequential index of this chunk in the stream
- networkTime?: number; // Time elapsed since previous chunk (milliseconds)
- processingTime?: number; // Time spent processing/parsing the chunk (milliseconds)
- chunkSize: number; // Size of chunk data in bytes
- type: 'content' | 'thinking' | 'tool' | 'debug'; // Type of content in this chunk
-}
-
-/**
- * Aggregated performance metrics for an entire stream
- */
-interface PerformanceMetrics {
- totalChunks: number; // Total number of chunks received
- averageNetworkTime: number; // Average time between chunks (milliseconds)
- averageProcessingTime: number; // Average processing time per chunk (milliseconds)
- totalDuration: number; // Total stream duration (milliseconds)
- slowestChunk: ChunkMetric | null; // Chunk with highest total latency
- chunksPerSecond: number; // Throughput in chunks per second
-}
-
-/**
- * Global debug interface exposed on window object
- */
-interface ChatDebugInterface {
- enable: () => void; // Enable performance monitoring
- disable: () => void; // Disable performance monitoring
- metrics: () => PerformanceMetrics; // Get current performance metrics
-}
-
-/**
- * Extend Window interface with chatDebug property
- */
-declare global {
- interface Window {
- chatDebug: ChatDebugInterface;
- }
-}
+import type { TChunkMetric, TPerformanceMetrics } from '@react/features/ai-chat/types';
/**
* Maximum number of chunks to track before cleanup
@@ -76,7 +36,7 @@ const MAX_METRICS_SIZE = 10000;
class PerformanceMonitor {
private enabled: boolean = false;
- private metrics: ChunkMetric[] = [];
+ private metrics: TChunkMetric[] = [];
private streamStartTime: number = 0;
private lastChunkTime: number = 0;
private chunkIndex: number = 0;
@@ -139,13 +99,13 @@ class PerformanceMonitor {
* @param chunkData - Raw chunk data received
* @param type - Type of chunk content
*/
- recordChunkArrival(chunkData: string, type: ChunkMetric['type'] = 'content'): void {
+ recordChunkArrival(chunkData: string, type: TChunkMetric['type'] = 'content'): void {
if (!this.enabled) return;
const now = performance.now();
const networkTime = now - this.lastChunkTime;
- const metric: ChunkMetric = {
+ const metric: TChunkMetric = {
timestamp: now,
chunkIndex: this.chunkIndex++,
networkTime,
@@ -194,34 +154,34 @@ class PerformanceMonitor {
if (!this.enabled) return;
const totalDuration = performance.now() - this.streamStartTime;
- const metrics = this.getMetrics();
+ const metricsResult = this.getMetrics();
this.log('%c✅ STREAM COMPLETED', 'color: #00ff00; font-weight: bold; font-size: 14px');
this.log(`⏱️ Total Duration: ${totalDuration.toFixed(2)}ms`);
- this.log(`📦 Total Chunks: ${metrics.totalChunks}`);
- this.log(`⚡ Chunks/Second: ${metrics.chunksPerSecond.toFixed(2)}`);
+ this.log(`📦 Total Chunks: ${metricsResult.totalChunks}`);
+ this.log(`⚡ Chunks/Second: ${metricsResult.chunksPerSecond.toFixed(2)}`);
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(` 🌐 Network (avg): ${metricsResult.averageNetworkTime.toFixed(2)}ms`);
+ this.log(` ⚙️ Processing (avg): ${metricsResult.averageProcessingTime.toFixed(2)}ms`);
- if (metrics.slowestChunk) {
+ if (metricsResult.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(` Size: ${metrics.slowestChunk.chunkSize} bytes`);
+ this.log(` Index: #${metricsResult.slowestChunk.chunkIndex}`);
+ this.log(` Network: ${metricsResult.slowestChunk.networkTime?.toFixed(2)}ms`);
+ this.log(` Processing: ${metricsResult.slowestChunk.processingTime?.toFixed(2)}ms`);
+ this.log(` Size: ${metricsResult.slowestChunk.chunkSize} bytes`);
}
// Identify bottleneck
- this.identifyBottleneck(metrics);
+ this.identifyBottleneck(metricsResult);
}
/**
* Analyzes metrics and identifies the bottleneck
- * @param metrics - Performance metrics to analyze
+ * @param performanceMetrics - Performance metrics to analyze
*/
- private identifyBottleneck(metrics: PerformanceMetrics): void {
- const { averageNetworkTime, averageProcessingTime } = metrics;
+ private identifyBottleneck(performanceMetrics: TPerformanceMetrics): void {
+ const { averageNetworkTime, averageProcessingTime } = performanceMetrics;
this.log('\n🎯 BOTTLENECK ANALYSIS:');
@@ -251,7 +211,7 @@ class PerformanceMonitor {
/**
* Gets computed metrics
*/
- getMetrics(): PerformanceMetrics {
+ getMetrics(): TPerformanceMetrics {
const totalChunks = this.metrics.length;
if (totalChunks === 0) {
@@ -268,8 +228,8 @@ class PerformanceMonitor {
const totalDuration = performance.now() - this.streamStartTime;
// Calculate averages
- const 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 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 averageNetworkTime =
networkTimes.length > 0 ? networkTimes.reduce((a, b) => a + b, 0) / networkTimes.length : 0;
@@ -280,8 +240,8 @@ class PerformanceMonitor {
// Find slowest chunk (by total time)
const slowestChunk = this.metrics.reduce((slowest, current) => {
- const currentTotal = (current.networkTime || 0) + (current.processingTime || 0);
- const slowestTotal = (slowest.networkTime || 0) + (slowest.processingTime || 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]);
@@ -350,3 +310,4 @@ if (typeof window !== 'undefined') {
metrics: () => performanceMonitor.getMetrics(),
};
}
+
diff --git a/packages/app/src/react/features/ai-chat/utils/stream.ts b/packages/app/src/react/features/ai-chat/utils/stream.ts
index 14447674..85ed0485 100644
--- a/packages/app/src/react/features/ai-chat/utils/stream.ts
+++ b/packages/app/src/react/features/ai-chat/utils/stream.ts
@@ -3,7 +3,7 @@
* Stream processing utilities for chat responses
*/
-import { IStreamChunk, TThinkingType } from '@react/features/ai-chat/types/chat.types';
+import { TStreamChunk, TThinkingType } from '@react/features/ai-chat/types';
/** Function-specific thinking messages that cycle during function execution */
const FUNCTION_THINKING_MESSAGES = [
@@ -30,7 +30,7 @@ const GENERAL_THINKING_MESSAGES = [
* @param data - Raw string data from stream
* @returns Array of parsed JSON objects
*/
-export const splitJSONStream = (data: string): IStreamChunk[] => {
+export const splitJSONStream = (data: string): TStreamChunk[] => {
if (!data || typeof data !== 'string') return [];
const cleanData = data.trim();
@@ -62,12 +62,12 @@ export const splitJSONStream = (data: string): IStreamChunk[] => {
return null;
}
- return JSON.parse(str) as IStreamChunk;
+ return JSON.parse(str) as TStreamChunk;
} catch {
return null;
}
})
- .filter((chunk): chunk is IStreamChunk => chunk !== null);
+ .filter((chunk): chunk is TStreamChunk => chunk !== null);
return parsedChunks;
};
@@ -194,7 +194,7 @@ export const createThinkingManager = (): ThinkingMessageManager => new ThinkingM
* @param chunk - Stream chunk to process
* @returns Processed chunk data
*/
-export const processStreamChunk = (chunk: IStreamChunk) => {
+export const processStreamChunk = (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.ts
new file mode 100644
index 00000000..0f6a39e4
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/utils/textarea.ts
@@ -0,0 +1,22 @@
+/**
+ * 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,
+): void => {
+ if (!textarea) return;
+
+ textarea.style.height = 'auto';
+ const newHeight = Math.min(textarea.scrollHeight, maxHeight);
+ textarea.style.height = `${newHeight}px`;
+ textarea.style.overflowY = newHeight === maxHeight ? 'auto' : 'hidden';
+};
+