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.

Perf/optimize agent chat UI and code (#110)

Salman Ahamedbd1a5c1fb146
diff --git a/packages/app/src/react/features/agents/components/agentCard/hooks/useAgentOperations.ts b/packages/app/src/react/features/agents/components/agentCard/hooks/useAgentOperations.ts
index 666e5fe9..db89a69e 100644
--- a/packages/app/src/react/features/agents/components/agentCard/hooks/useAgentOperations.ts
+++ b/packages/app/src/react/features/agents/components/agentCard/hooks/useAgentOperations.ts
@@ -1,7 +1,8 @@
import { DuplicateAgentResponse, IAgent } from '@react/features/agents/components/agentCard/types';
import { accquireLock } from '@react/features/agents/utils';
-import { useAgentMutations } from '@react/shared/hooks/agent';
+import { Agent, AgentData } from '@src/react/shared/types/agent-data.types';
import { builderStore } from '@src/shared/state_stores/builder/store';
+import { useQueryClient } from '@tanstack/react-query';
import { useCallback } from 'react';
import { toast } from 'react-toastify';
@@ -19,6 +20,69 @@ interface UseAgentOperationsResult {
isLoading: boolean;
}
+interface SaveAgentResponse {
+ success: boolean;
+ agent: Agent;
+}
+
+interface CreateAgentResponse {
+ id: string;
+ name: string;
+ success: boolean;
+}
+
+interface CreateAgent {
+ name: string;
+ behavior?: string;
+ description?: string;
+ domain?: string[];
+ data?: AgentData;
+}
+
+export const useAgentMutations = () => {
+ const queryClient = useQueryClient();
+
+ const createAgent = async (agentData: CreateAgent): Promise<CreateAgentResponse> => {
+ const response = await fetch('/api/agent', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(agentData),
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to create agent');
+ }
+
+ const data = await response.json();
+ await queryClient.invalidateQueries(['agents']); // Invalidate agents list
+ return data;
+ };
+
+ const saveAgent = async (
+ agentId: string,
+ agentData: Partial<Agent>,
+ ): Promise<SaveAgentResponse> => {
+ const response = await fetch(`/api/agent/${agentId}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify(agentData),
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to save agent');
+ }
+
+ const data = await response.json();
+ await queryClient.invalidateQueries(['agent_data', agentId]); // Invalidate specific agent data
+ await queryClient.invalidateQueries(['agents']); // Invalidate agents list
+ return data.agent;
+ };
+
+ return { createAgent, saveAgent };
+};
+
/**
* Custom hook for handling agent operations (duplicate, delete)
*/
@@ -30,7 +94,7 @@ export function useAgentOperations({
}: UseAgentOperationsProps): UseAgentOperationsResult {
// Only fetch full agent data when actually needed for duplication
// This prevents unnecessary API calls for every agent card
- const { createAgent, saveAgent } = useAgentMutations();
+ const { createAgent } = useAgentMutations();
/**
* Creates a duplicate of an existing agent with reset configurations
diff --git a/packages/app/src/react/features/ai-chat/components/chat-bubble.tsx b/packages/app/src/react/features/ai-chat/components/chat-bubble.tsx
deleted file mode 100644
index 949a0205..00000000
--- a/packages/app/src/react/features/ai-chat/components/chat-bubble.tsx
+++ /dev/null
@@ -1,304 +0,0 @@
-
-/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */
-import { Tooltip } from 'flowbite-react';
-import { FC, useRef, useState } from 'react';
-import { FaCheck, FaRegCopy } from 'react-icons/fa6';
-import ReactMarkdown from 'react-markdown';
-import remarkGfm from 'remark-gfm';
-
-import '../styles/index.css';
-
-import {
- CodeBlockWithCopyButton,
- FileItemPreview,
- ReplyLoader,
- ThinkingMessage,
-} from '@react/features/ai-chat/components';
-import { FileWithMetadata, IChatMessage } from '@react/shared/types/chat.types';
-import { Tooltip } from 'flowbite-react';
-import { FC, useRef, useState } from 'react';
-import { FaCheck, FaRegCopy } from 'react-icons/fa6';
-import ReactMarkdown from 'react-markdown';
-import remarkGfm from 'remark-gfm';
-import '../styles/index.css';
-
-
-const DEFAULT_AVATAR_URL =
- 'https://gravatar.com/avatar/ccd5b19e810febbfd3d4321e27b15f77?s=400&d=mp&r=x';
-
-// Re-export the interface for use in other components
-export type { IChatMessage };
-
-export const ChatBubble: FC<IChatMessage> = ({
- me,
- files,
- avatar,
- isLast,
- message,
- type,
- isReplying,
- isRetrying,
- onRetryClick,
- isError = false,
- hideMessageBubble,
- thinkingMessage,
-}) => {
- if (me) {
- return (
- <UserMessageBubble message={message} files={files} hideMessageBubble={hideMessageBubble} />
- );
- }
-
- // Handle thinking messages
- if (type === 'thinking') return <ThinkingMessage message={message} avatar={avatar} />;
-
- return isReplying || isRetrying ? (
- <ReplyLoader avatar={avatar ?? DEFAULT_AVATAR_URL} />
- ) : (
- <div className={me ? 'pl-[100px]' : ''}>
- {!hideMessageBubble && (
- <SystemMessageBubble
- avatar={avatar}
- message={message}
- isError={isError}
- onRetryClick={onRetryClick}
- isRetrying={isRetrying}
- thinkingMessage={thinkingMessage}
- />
- )}
- </div>
- );
-};
-
-interface IUserMessageBubble {
- message: string;
- files?: FileWithMetadata[];
- hideMessageBubble?: boolean;
-}
-
-const UserMessageBubble: FC<IUserMessageBubble> = ({ message, files, hideMessageBubble }) => {
- return (
- <div className="break-all flex flex-col items-end">
- {files && files.length > 0 && (
- <div className="flex flex-nowrap gap-2 mb-2 overflow-x-auto">
- {files.map((fileWithKey, index) => (
- <FileItemPreview
- isReadOnly
- key={index}
- file={fileWithKey}
- fileKey={fileWithKey.metadata.key}
- inChatBubble={true}
- />
- ))}
- </div>
- )}
- {!hideMessageBubble && message && (
- <div className="rounded-[18px] bg-[#f4f4f4] text-[#2b2b2b] p-3 px-4 w-fit whitespace-pre-wrap text-wrap max-w-[535px]">
- {message}
- </div>
- )}
- </div>
- );
-};
-
-interface ISystemMessageBubble {
- message: string;
- avatar?: string;
- isError?: boolean;
- isRetrying?: boolean;
- onRetryClick?: () => void;
- thinkingMessage?: string;
-}
-
-const SystemMessageBubble: FC<ISystemMessageBubble> = ({
- avatar,
- message,
- isError,
- isRetrying,
- onRetryClick,
- thinkingMessage,
-}) => {
- const [copied, setCopied] = useState(false);
- const contentRef = useRef<HTMLDivElement>(null);
-
- const handleCopy = () => {
- if (contentRef.current) {
- const range = document.createRange();
- range.selectNodeContents(contentRef.current);
- const selection = window.getSelection();
- selection?.removeAllRanges();
- selection?.addRange(range);
-
- try {
- document.execCommand('copy');
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } catch (err) {
- console.error('Failed to copy text: ', err); // eslint-disable-line no-console
- }
-
- selection?.removeAllRanges();
- }
- };
-
- return (
- <div className="system-message-bubble relative">
- <div className="flex-1" ref={contentRef}>
- {isError ? (
- <ErrorMessageBubble
- message={message}
- onRetryClick={onRetryClick}
- isRetrying={isRetrying}
- />
- ) : (
- <div className="chat-rich-text-response space-y-1 rounded-lg p-3 text-[#141414]">
- <ReactMarkdown
- children={message}
- remarkPlugins={[remarkGfm]}
- components={{
- // adding components to ensure formatting is preserved
- h1: ({ node, ...props }) => (
- <h1 style={{ fontWeight: 'bold', fontSize: '2em' }} {...props} />
- ),
- h2: ({ node, ...props }) => (
- <h2 style={{ fontWeight: 'bold', fontSize: '1.5em' }} {...props} />
- ),
- h3: ({ node, ...props }) => (
- <h3 style={{ fontWeight: 'bold', fontSize: '1.17em' }} {...props} />
- ),
- h4: ({ node, ...props }) => (
- <h4 style={{ fontWeight: 'bold', fontSize: '1em' }} {...props} />
- ),
- h5: ({ node, ...props }) => (
- <h5 style={{ fontWeight: 'bold', fontSize: '0.83em' }} {...props} />
- ),
- h6: ({ node, ...props }) => (
- <h6 style={{ fontWeight: 'bold', fontSize: '0.67em' }} {...props} />
- ),
- code({ node, className, children, ...props }) {
- const match = /language-(\w+)/.exec(className || '');
- return match ? (
- <CodeBlockWithCopyButton language={match[1]}>
- {String(children).replace(/\n$/, '')}
- </CodeBlockWithCopyButton>
- ) : (
- <code className={className} {...props}>
- {children}
- </code>
- );
- },
- img: ({ node, ...props }) => (
- <img
- {...props}
- className="rounded-xl"
- style={{ maxWidth: '100%', height: 'auto' }}
- />
- ),
- a: ({ node, ...props }) => (
- <a {...props} target="_blank" rel="noopener noreferrer" />
- ),
- p: ({ children }) => <p className="whitespace-pre-wrap">{children}</p>,
- }}
- />
-
- {/* Display thinking message inline if present */}
- {thinkingMessage && <ThinkingMessage message={thinkingMessage} avatar={avatar} />}
- </div>
- )}
- </div>
- {!isError && !thinkingMessage && (
- <div className="flex gap-4 p-4 pl-0">
- <Tooltip content={copied ? 'Copied!' : 'Copy'} placement="bottom">
- <button
- onClick={handleCopy}
- className="text-gray-500 hover:text-gray-700 transition-colors"
- >
- {copied ? <FaCheck /> : <FaRegCopy />}
- </button>
- </Tooltip>
- </div>
- )}
- </div>
- );
-};
-
-const ErrorMessageBubble: FC<{
- message: string;
- onRetryClick: () => void;
- isRetrying?: boolean;
-}> = ({ message, onRetryClick, isRetrying }) => {
- // Check if this is a 401 API key error
-
- const isApiKeyError =
- message.includes('Incorrect API key provided') ||
- (message.includes('401') &&
- message.toLowerCase().includes('api') &&
- message.toLocaleLowerCase().includes('key'));
-
- return (
- <div className="flex flex-col items-start">
- <div className="rounded-lg bg-pink-50 border border-pink-200 p-4 max-w-screen-md flex justify-between items-center gap-5">
- <div className="flex items-start gap-3">
- <div className="flex-shrink-0 mt-0.5">
- <svg
- width="20"
- height="20"
- viewBox="0 0 20 20"
- fill="currentColor"
- xmlns="http://www.w3.org/2000/svg"
- className="text-red-500"
- >
- <path d="M10 9.25C10.4142 9.25002 10.75 9.5858 10.75 10V13.333C10.75 13.7472 10.4142 14.083 10 14.083C9.58579 14.083 9.25 13.7472 9.25 13.333V10C9.25 9.58579 9.58579 9.25 10 9.25Z"></path>
- <path d="M10 5.83301C10.5293 5.83303 10.958 6.26273 10.958 6.79199C10.9578 7.3211 10.5291 7.74998 10 7.75C9.47084 7.75 9.04217 7.32111 9.04199 6.79199C9.04199 6.26272 9.47073 5.83301 10 5.83301Z"></path>
- <path
- fillRule="evenodd"
- clipRule="evenodd"
- d="M10 2.08496C14.3713 2.08496 17.915 5.62867 17.915 10C17.915 14.3713 14.3713 17.915 10 17.915C5.62867 17.915 2.08496 14.3713 2.08496 10C2.08496 5.62867 5.62867 2.08496 10 2.08496ZM10 3.41504C6.3632 3.41504 3.41504 6.3632 3.41504 10C3.41504 13.6368 6.3632 16.585 10 16.585C13.6368 16.585 16.585 13.6368 16.585 10C16.585 6.3632 13.6368 3.41504 10 3.41504Z"
- ></path>
- </svg>
- </div>
-
- <div className="flex-1 text-red-700 text-sm leading-relaxed">
- {isApiKeyError && (
- <>
- <h6 className="font-bold">Invalid API Key</h6>
- <p>
- The API key you provided is not valid. Please set a valid key to continue:&nbsp;
- <a
- href="/vault"
- target="_blank"
- className="text-red-700 hover:text-red-900 font-semibold"
- >
- Set API Key
- </a>
- </p>
- <h6 className="font-semibold pt-1">Error details:</h6>
- </>
- )}
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{message}</ReactMarkdown>
- </div>
- </div>
- {onRetryClick && !isRetrying && (
- <button
- disabled={isRetrying}
- onClick={onRetryClick}
- className="inline-flex items-center px-4 gap-x-1 py-2 border border-gray-300 text-sm font-medium rounded-[18px] text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-sm"
- >
- <svg
- width="20"
- height="20"
- viewBox="0 0 20 20"
- fill="currentColor"
- xmlns="http://www.w3.org/2000/svg"
- aria-label=""
- className="-ms-0.5 icon"
- >
- <path d="M16.4183 9.99967C16.4181 6.45518 13.5448 3.58188 10.0003 3.58171C7.96895 3.58171 6.15935 4.52712 4.98273 6.00163H7.50031L7.6341 6.0153C7.93707 6.07735 8.16535 6.34535 8.16535 6.66667C8.16535 6.98799 7.93707 7.25598 7.6341 7.31803L7.50031 7.33171H3.75031C3.73055 7.33171 3.71104 7.32656 3.69172 7.32487C3.68913 7.32464 3.68649 7.32513 3.68391 7.32487C3.64304 7.32082 3.60409 7.31254 3.56574 7.30143C3.56188 7.30031 3.55788 7.2997 3.55402 7.2985C3.51366 7.286 3.47546 7.27023 3.43879 7.25065L3.43586 7.24967C3.43444 7.24891 3.43337 7.24752 3.43195 7.24675C3.35757 7.20587 3.29219 7.15262 3.23859 7.08757C3.23505 7.08329 3.23128 7.07923 3.22785 7.07487C3.20549 7.04631 3.1858 7.01609 3.16828 6.98405C3.16491 6.97791 3.16169 6.97173 3.15852 6.9655C3.14408 6.93698 3.13265 6.90732 3.12238 6.87663C3.11744 6.86205 3.11264 6.84757 3.10871 6.83268C3.10316 6.81117 3.09843 6.78955 3.09504 6.76725C3.09108 6.74233 3.08833 6.71738 3.08723 6.69206C3.08691 6.68361 3.08527 6.67519 3.08527 6.66667V2.91667C3.08527 2.5494 3.38304 2.25163 3.75031 2.25163C4.11743 2.2518 4.41535 2.54951 4.41535 2.91667V4.62956C5.82462 3.16447 7.80565 2.25163 10.0003 2.25163C14.2793 2.2518 17.7482 5.72065 17.7484 9.99967C17.7484 14.2789 14.2794 17.7485 10.0003 17.7487C6.02899 17.7487 2.75629 14.7612 2.305 10.9108L2.96516 10.8337L3.62531 10.7555C3.99895 13.9437 6.7115 16.4186 10.0003 16.4186C13.5449 16.4184 16.4183 13.5443 16.4183 9.99967ZM2.88801 10.1725C3.25252 10.13 3.58237 10.3911 3.62531 10.7555L2.305 10.9108C2.26225 10.546 2.52323 10.2153 2.88801 10.1725Z"></path>
- </svg>
- {isRetrying ? 'Retrying...' : 'Retry'}
- </button>
- )}
- </div>
- </div>
- );
-};
diff --git a/packages/app/src/react/features/ai-chat/components/chat-container.tsx b/packages/app/src/react/features/ai-chat/components/chat-container.tsx
deleted file mode 100644
index 08008705..00000000
--- a/packages/app/src/react/features/ai-chat/components/chat-container.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import { FC, ReactNode } from 'react';
-
-interface IChildren {
- children: ReactNode;
-}
-
-export const ChatContainer: FC<IChildren> = ({ children }) => (
- <div className="w-full h-full flex flex-col items-center justify-end px-4 md:px-0 ph-no-capture">
- {children}
- </div>
-);
diff --git a/packages/app/src/react/features/ai-chat/components/chat-header.tsx b/packages/app/src/react/features/ai-chat/components/chat-header.tsx
deleted file mode 100644
index 4225c577..00000000
--- a/packages/app/src/react/features/ai-chat/components/chat-header.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { Tooltip } from 'flowbite-react';
-import { FC } from 'react';
-import { FaRegPenToSquare } from 'react-icons/fa6';
-import { Link } from 'react-router-dom';
-
-import { useChatContext } from '@react/features/ai-chat/contexts';
-import { CloseIcon } from './icons';
-
-interface ChatHeaderProps {
- agentName: string;
- avatar?: string;
-}
-
-export const ChatHeader: FC<ChatHeaderProps> = ({ agentName, avatar }) => {
- const { clearChatSession } = useChatContext();
-
- return (
- <div className="w-full bg-white border-b border-[#e5e5e5] h-14 flex justify-center absolute top-0 left-0 z-10">
- <div className="w-full max-w-4xl flex justify-between items-center">
- {/* Left side - Avatar and Agent Name */}
- <div className="flex items-center gap-3">
- <img src={avatar} alt="avatar" className="w-8 h-8 rounded-full" />
- <div className="text-lg font-medium text-[#111827]">{agentName}</div>
- </div>
-
- {/* Right side - Action buttons */}
- <div className="flex items-center justify-center gap-2">
- <Tooltip content={<>New&nbsp;Chat</>} placement="bottom">
- <button
- className="cursor-pointer w-6 h-6 flex items-center justify-center"
- onClick={clearChatSession}
- >
- <FaRegPenToSquare className="text-gray-500 w-4 h-4" />
- </button>
- </Tooltip>
- <Tooltip content="Exit" placement="bottom">
- <Link to="/agents">
- <CloseIcon className="text-gray-500 w-6 h-6" />
- </Link>
- </Tooltip>
- </div>
- </div>
- </div>
- );
-};
diff --git a/packages/app/src/react/features/ai-chat/components/chat-history.tsx b/packages/app/src/react/features/ai-chat/components/chat-history.tsx
deleted file mode 100644
index 587d2f15..00000000
--- a/packages/app/src/react/features/ai-chat/components/chat-history.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { debounce } from 'lodash-es';
-import { FC, useCallback, useEffect, useRef, useState } from 'react';
-import { useInView } from 'react-intersection-observer';
-
-import { ChatBubble } from '@react/features/ai-chat/components';
-import { CHAT_ERROR_MESSAGE } from '@react/features/ai-chat/constants';
-import { useChatContext } from '@react/features/ai-chat/contexts';
-import { useChatMessagesSuspendedQuery } from '@react/features/ai-chat/hooks';
-import { AgentDetails } from '@react/shared/types/agent-data.types';
-import { IChatMessage } from '@react/shared/types/chat.types';
-
-interface ChatHistoryProps {
- chatId: string;
- agent: AgentDetails;
- messages: IChatMessage[];
-}
-
-export const ChatHistory: FC<ChatHistoryProps> = ({ agent, chatId, messages }) => {
- const { chatHistoryMessages, isRetrying: contextIsRetrying, retryLastMessage } = useChatContext();
- const [page, setPage] = useState(1);
- const [hasMore, setHasMore] = useState(true);
- const [hasError, setHasError] = useState(false);
- const messagesContainer = useRef<HTMLDivElement>(null);
- const [isLoadingMore, setIsLoadingMore] = useState(false);
- const avatar = agent?.aiAgentSettings?.avatar;
- const LIMIT = 25;
-
- const { inView: topInView } = useInView({ threshold: 0 });
-
- const { isFetching } = useChatMessagesSuspendedQuery(
- { agentId: agent?.id, chatId: chatId, page: page, limit: LIMIT },
- { enabled: false, retry: false },
- );
-
- useEffect(() => {
- setPage(1);
- setHasMore(true);
- setHasError(false);
- }, [chatId]);
-
- const loadMoreMessages = useCallback(() => {
- if (!isFetching && hasMore && !isLoadingMore && !hasError) {
- // TEMPORARY FIX TO AVOID PAGE
- if (messages.length > 0) {
- setIsLoadingMore(true);
- setPage((prevPage) => prevPage + 1);
- }
- }
- }, [isFetching, hasMore, isLoadingMore, hasError]); // eslint-disable-line react-hooks/exhaustive-deps
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- const debouncedLoadMoreMessages = useCallback(debounce(loadMoreMessages, 300), [
- loadMoreMessages,
- ]);
-
- useEffect(() => {
- if (topInView && hasMore && !isLoadingMore) {
- debouncedLoadMoreMessages();
- }
- }, [topInView, debouncedLoadMoreMessages, hasMore, isLoadingMore]);
-
- useEffect(() => {
- if (!messagesContainer.current) return;
- messagesContainer.current.scrollTop = messagesContainer.current.scrollHeight;
- }, [messages]);
-
- return (
- <div className="w-full flex flex-col items-center">
- <div
- className="flex-1 h-screen overflow-y-auto scrollbar-hide pb-4 flex flex-col items-center w-full"
- ref={messagesContainer}
- >
- <div className="flex flex-col gap-6 max-w-4xl w-full">
- {hasError && <ErrorMessage avatar={avatar} />}
- {chatHistoryMessages.map((message, index) => (
- <div key={index}>
- <ChatBubble
- {...message}
- avatar={avatar}
- onRetryClick={
- index === chatHistoryMessages.length - 1 && message.isError
- ? retryLastMessage
- : undefined
- }
- isRetrying={contextIsRetrying && index === chatHistoryMessages.length - 1}
- // Handle error messages as normal responses with error styling
- isError={message.isError}
- errorType={message.errorType}
- />
- {index === chatHistoryMessages.length - 1 && contextIsRetrying && (
- <button onClick={retryLastMessage}>Retry</button>
- )}
- </div>
- ))}
- </div>
- </div>
- </div>
- );
-};
-
-const ErrorMessage: FC<{ avatar?: string }> = ({ avatar }) => (
- <ChatBubble isError message={CHAT_ERROR_MESSAGE} avatar={avatar} me={false} />
-);
diff --git a/packages/app/src/react/features/ai-chat/components/chat.tsx b/packages/app/src/react/features/ai-chat/components/chat.tsx
new file mode 100644
index 00000000..13479197
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/chat.tsx
@@ -0,0 +1,50 @@
+import { FC } from 'react';
+
+import {
+ ReplyLoader,
+ SystemMessage,
+ ThinkingMessage,
+ UserMessage,
+} from '@react/features/ai-chat/components';
+import { IChatMessage } from '@react/shared/types/chat.types';
+
+import '../styles/index.css';
+
+interface ChatProps extends IChatMessage {
+ scrollToBottom?: () => void;
+}
+
+export const Chat: FC<ChatProps> = ({
+ me,
+ files,
+ avatar,
+ message,
+ type,
+ isReplying,
+ isRetrying,
+ onRetryClick,
+ isError = false,
+ hideMessage,
+ thinkingMessage,
+ scrollToBottom,
+}) => {
+ if (isReplying || isRetrying) return <ReplyLoader />;
+ if (me && !hideMessage) return <UserMessage message={message} files={files} />;
+ if (type === 'thinking') return <ThinkingMessage message={message} avatar={avatar} />;
+
+ return (
+ !hideMessage && (
+ <SystemMessage
+ avatar={avatar}
+ message={message}
+ isError={isError}
+ onRetryClick={onRetryClick}
+ isRetrying={isRetrying}
+ thinkingMessage={thinkingMessage}
+ onTypingProgress={() => scrollToBottom?.()}
+ onTypingComplete={() => scrollToBottom?.()}
+ typingAnimation={!isReplying && !isRetrying && !isError}
+ />
+ )
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/chats.tsx b/packages/app/src/react/features/ai-chat/components/chats.tsx
new file mode 100644
index 00000000..a95356db
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/chats.tsx
@@ -0,0 +1,96 @@
+/* eslint-disable no-unused-vars */
+import { Chat, ScrollToBottomButton } from '@react/features/ai-chat/components';
+import { useChatContext } from '@react/features/ai-chat/contexts';
+import { useDragAndDrop } from '@react/features/ai-chat/hooks';
+import { AgentDetails } from '@src/react/shared/types/agent-data.types';
+import { IChatMessage } from '@src/react/shared/types/chat.types';
+import { FC, MutableRefObject, RefObject, useEffect, useRef } from 'react';
+
+interface MessagesProps {
+ agent: AgentDetails;
+ messages: IChatMessage[];
+ handleScroll: () => void;
+ showScrollButton: boolean;
+ containerRef: RefObject<HTMLElement>;
+ scrollToBottom: (smooth?: boolean) => void;
+ smartScrollToBottom: (smooth?: boolean) => void;
+ handleFileDrop: (droppedFiles: File[]) => Promise<void>;
+}
+
+/**
+ * Combines multiple refs into a single ref callback
+ */
+const combineRefs =
+ <T extends HTMLElement>(...refs: Array<RefObject<T> | MutableRefObject<T | null>>) =>
+ (element: T | null) => {
+ refs.forEach((ref) => {
+ if (!ref) return;
+ (ref as MutableRefObject<T | null>).current = element;
+ });
+ };
+
+export const Chats: FC<MessagesProps> = (props) => {
+ const { agent, messages, containerRef, handleFileDrop, ...scroll } = props;
+ const { handleScroll, scrollToBottom, smartScrollToBottom, showScrollButton } = scroll;
+
+ const ref = useRef<HTMLDivElement>(null);
+ const { isRetrying, retryLastMessage } = useChatContext();
+ const dropzoneRef = useDragAndDrop({ onDrop: handleFileDrop });
+
+ // Smart auto-scroll when new messages arrive (respects user scroll position)
+ // But only for system messages, not user messages (user messages handle their own scroll)
+ useEffect(() => {
+ const lastMessage = messages[messages.length - 1];
+ // Only auto-scroll for system messages, not user messages
+ // lastMessage.me === false means it's a system message
+ if (lastMessage && !lastMessage.me) {
+ smartScrollToBottom();
+ }
+ }, [messages, smartScrollToBottom]);
+
+ const avatar = agent?.aiAgentSettings?.avatar;
+
+ return (
+ <div
+ data-chat-container
+ onScroll={handleScroll}
+ ref={combineRefs(containerRef, dropzoneRef)}
+ className="w-full h-full overflow-auto relative scroll-smooth mt-16 flex justify-center items-center"
+ >
+ <div
+ className="w-full h-full max-w-4xl"
+ onScroll={handleScroll}
+ ref={combineRefs(containerRef, dropzoneRef)}
+ >
+ <div className="w-full flex-1 pb-4 space-y-6 px-2.5" ref={ref}>
+ {messages.map((message, i) => {
+ const isLast = i === messages.length - 1;
+ const onRetryClick = message.isError && isLast ? retryLastMessage : undefined;
+ const retry = isRetrying && isLast;
+
+ return (
+ <div key={i}>
+ <Chat
+ {...message}
+ avatar={avatar}
+ isRetrying={retry}
+ isError={message.isError}
+ onRetryClick={onRetryClick}
+ scrollToBottom={smartScrollToBottom}
+ />
+
+ {retry && (
+ <button onClick={retryLastMessage} className="pt-1.5">
+ Retry
+ </button>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ {showScrollButton && <ScrollToBottomButton onClick={() => scrollToBottom(true)} />}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/code-block-with-copy-button.tsx b/packages/app/src/react/features/ai-chat/components/code-block.tsx
similarity index 89%
rename from packages/app/src/react/features/ai-chat/components/code-block-with-copy-button.tsx
rename to packages/app/src/react/features/ai-chat/components/code-block.tsx
index cebe440f..ba043877 100644
--- a/packages/app/src/react/features/ai-chat/components/code-block-with-copy-button.tsx
+++ b/packages/app/src/react/features/ai-chat/components/code-block.tsx
@@ -3,15 +3,12 @@ import { FaCheck, FaRegCopy } from 'react-icons/fa';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { materialDark } from 'react-syntax-highlighter/dist/esm/styles/prism';
-interface CodeBlockWithCopyButtonProps {
+interface CodeBlock {
language: string;
children: string;
}
-export const CodeBlockWithCopyButton: FC<CodeBlockWithCopyButtonProps> = ({
- language,
- children,
-}) => {
+export const CodeBlock: FC<CodeBlock> = ({ language, children }) => {
const [isCopied, setIsCopied] = useState(false);
const handleCopyClick = () => {
diff --git a/packages/app/src/react/features/ai-chat/components/container.tsx b/packages/app/src/react/features/ai-chat/components/container.tsx
new file mode 100644
index 00000000..e0562040
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/container.tsx
@@ -0,0 +1,54 @@
+import { FC, ReactNode, useCallback, useEffect, useRef } from 'react';
+
+interface ContainerProps {
+ children: ReactNode;
+}
+
+/**
+ * Container component that overrides parent max-width constraint
+ * to provide full-width layout for chat interface
+ */
+export const Container: FC<ContainerProps> = ({ children }) => {
+ const parentElementRef = useRef<HTMLElement | null>(null);
+ const originalStateRef = useRef<{ className: string; maxWidth: string } | null>(null);
+
+ const overrideParentWidth = useCallback(() => {
+ const containerElement = document.querySelector('.ph-no-capture') as HTMLElement;
+ if (!containerElement?.parentElement) return;
+
+ const parent = containerElement.parentElement;
+ parentElementRef.current = parent;
+
+ // Store original state
+ originalStateRef.current = {
+ className: parent.className,
+ maxWidth: parent.style.maxWidth,
+ };
+
+ // Override max-width constraint
+ parent.classList.remove('max-w-[1224px]');
+ parent.classList.add('max-w-none');
+ parent.style.maxWidth = 'none';
+ }, []);
+
+ const restoreParentWidth = useCallback(() => {
+ const parent = parentElementRef.current;
+ const originalState = originalStateRef.current;
+
+ if (!parent || !originalState) return;
+
+ parent.className = originalState.className;
+ parent.style.maxWidth = originalState.maxWidth;
+ }, []);
+
+ useEffect(() => {
+ overrideParentWidth();
+ return restoreParentWidth;
+ }, [overrideParentWidth, restoreParentWidth]);
+
+ return (
+ <div className="w-full h-full flex flex-col items-center justify-end px-2.5 md:px-0 ph-no-capture mx-auto relative bg-white">
+ {children}
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/error-message.tsx b/packages/app/src/react/features/ai-chat/components/error-message.tsx
new file mode 100644
index 00000000..e14829b3
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/error-message.tsx
@@ -0,0 +1,86 @@
+import { FC } from 'react';
+import ReactMarkdown from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+
+interface IErrorMessage {
+ message: string;
+ onRetryClick: () => void;
+ isRetrying?: boolean;
+}
+
+export const ErrorMessage: FC<IErrorMessage> = ({ message, onRetryClick, isRetrying }) => {
+ // Check if this is a 401 API key error
+
+ const isApiKeyError =
+ message.includes('Incorrect API key provided') ||
+ (message.includes('401') &&
+ message.toLowerCase().includes('api') &&
+ message.toLocaleLowerCase().includes('key'));
+
+ return (
+ <div className="flex flex-col items-start">
+ <div className="rounded-lg bg-pink-50 border border-pink-200 p-4 max-w-screen-md flex justify-between items-center gap-5">
+ <div className="flex items-start gap-3">
+ <div className="flex-shrink-0 mt-0.5">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ xmlns="http://www.w3.org/2000/svg"
+ className="text-red-500"
+ >
+ <path d="M10 9.25C10.4142 9.25002 10.75 9.5858 10.75 10V13.333C10.75 13.7472 10.4142 14.083 10 14.083C9.58579 14.083 9.25 13.7472 9.25 13.333V10C9.25 9.58579 9.58579 9.25 10 9.25Z"></path>
+ <path d="M10 5.83301C10.5293 5.83303 10.958 6.26273 10.958 6.79199C10.9578 7.3211 10.5291 7.74998 10 7.75C9.47084 7.75 9.04217 7.32111 9.04199 6.79199C9.04199 6.26272 9.47073 5.83301 10 5.83301Z"></path>
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M10 2.08496C14.3713 2.08496 17.915 5.62867 17.915 10C17.915 14.3713 14.3713 17.915 10 17.915C5.62867 17.915 2.08496 14.3713 2.08496 10C2.08496 5.62867 5.62867 2.08496 10 2.08496ZM10 3.41504C6.3632 3.41504 3.41504 6.3632 3.41504 10C3.41504 13.6368 6.3632 16.585 10 16.585C13.6368 16.585 16.585 13.6368 16.585 10C16.585 6.3632 13.6368 3.41504 10 3.41504Z"
+ ></path>
+ </svg>
+ </div>
+
+ <div className="flex-1 text-red-700 text-sm leading-relaxed">
+ {isApiKeyError && (
+ <>
+ <h6 className="font-bold">Invalid API Key</h6>
+ <p>
+ The API key you provided is not valid. Please set a valid key to continue:&nbsp;
+ <a
+ href="/vault"
+ target="_blank"
+ className="text-red-700 hover:text-red-900 font-semibold"
+ >
+ Set API Key
+ </a>
+ </p>
+ <h6 className="font-semibold pt-1">Error details:</h6>
+ </>
+ )}
+ <ReactMarkdown remarkPlugins={[remarkGfm]}>{message}</ReactMarkdown>
+ </div>
+ </div>
+ {onRetryClick && !isRetrying && (
+ <button
+ disabled={isRetrying}
+ onClick={onRetryClick}
+ className="inline-flex items-center px-4 gap-x-1 py-2 border border-gray-300 text-sm font-medium rounded-[18px] text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-sm"
+ >
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ xmlns="http://www.w3.org/2000/svg"
+ aria-label=""
+ className="-ms-0.5 icon"
+ >
+ <path d="M16.4183 9.99967C16.4181 6.45518 13.5448 3.58188 10.0003 3.58171C7.96895 3.58171 6.15935 4.52712 4.98273 6.00163H7.50031L7.6341 6.0153C7.93707 6.07735 8.16535 6.34535 8.16535 6.66667C8.16535 6.98799 7.93707 7.25598 7.6341 7.31803L7.50031 7.33171H3.75031C3.73055 7.33171 3.71104 7.32656 3.69172 7.32487C3.68913 7.32464 3.68649 7.32513 3.68391 7.32487C3.64304 7.32082 3.60409 7.31254 3.56574 7.30143C3.56188 7.30031 3.55788 7.2997 3.55402 7.2985C3.51366 7.286 3.47546 7.27023 3.43879 7.25065L3.43586 7.24967C3.43444 7.24891 3.43337 7.24752 3.43195 7.24675C3.35757 7.20587 3.29219 7.15262 3.23859 7.08757C3.23505 7.08329 3.23128 7.07923 3.22785 7.07487C3.20549 7.04631 3.1858 7.01609 3.16828 6.98405C3.16491 6.97791 3.16169 6.97173 3.15852 6.9655C3.14408 6.93698 3.13265 6.90732 3.12238 6.87663C3.11744 6.86205 3.11264 6.84757 3.10871 6.83268C3.10316 6.81117 3.09843 6.78955 3.09504 6.76725C3.09108 6.74233 3.08833 6.71738 3.08723 6.69206C3.08691 6.68361 3.08527 6.67519 3.08527 6.66667V2.91667C3.08527 2.5494 3.38304 2.25163 3.75031 2.25163C4.11743 2.2518 4.41535 2.54951 4.41535 2.91667V4.62956C5.82462 3.16447 7.80565 2.25163 10.0003 2.25163C14.2793 2.2518 17.7482 5.72065 17.7484 9.99967C17.7484 14.2789 14.2794 17.7485 10.0003 17.7487C6.02899 17.7487 2.75629 14.7612 2.305 10.9108L2.96516 10.8337L3.62531 10.7555C3.99895 13.9437 6.7115 16.4186 10.0003 16.4186C13.5449 16.4184 16.4183 13.5443 16.4183 9.99967ZM2.88801 10.1725C3.25252 10.13 3.58237 10.3911 3.62531 10.7555L2.305 10.9108C2.26225 10.546 2.52323 10.2153 2.88801 10.1725Z"></path>
+ </svg>
+ {isRetrying ? 'Retrying...' : 'Retry'}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/error-toast.tsx b/packages/app/src/react/features/ai-chat/components/error-toast.tsx
index 8025eead..1997f209 100644
--- a/packages/app/src/react/features/ai-chat/components/error-toast.tsx
+++ b/packages/app/src/react/features/ai-chat/components/error-toast.tsx
@@ -8,9 +8,7 @@ interface ErrorToastProps {
}
export const ErrorToast: FC<ErrorToastProps> = ({ message, onClose }) => (
- <div
- className="bg-[#FEFBED] border border-solid border-[#FAEBA8] flex items-center justify-between max-w-full min-h-[42px] rounded-md p-3" // eslint-disable-line max-len
- >
+ <div className="bg-[#FEFBED] border border-solid border-[#FAEBA8] flex items-center justify-between w-full min-h-[42px] rounded-md p-3">
<div className="flex items-center gap-1.5">
<div className="flex-shrink-0">
<FaCircleExclamation style={{ color: '#88451D' }} />
diff --git a/packages/app/src/react/features/ai-chat/components/footer.tsx b/packages/app/src/react/features/ai-chat/components/footer.tsx
new file mode 100644
index 00000000..a64ed750
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/footer.tsx
@@ -0,0 +1,29 @@
+import {
+ ChatInput,
+ ErrorToast,
+ ChatInputRef,
+ WarningInfo,
+} from '@react/features/ai-chat/components';
+import { FC, RefObject } from 'react';
+
+interface FooterProps {
+ uploadError: { show: boolean; message: string };
+ clearError: () => void;
+ chatInputRef: RefObject<ChatInputRef>;
+ submitDisabled: boolean;
+}
+
+const CHAT_WARNING_INFO =
+ "SmythOS can make mistakes, always check your work. We don't store chat history, save important work."; // eslint-disable-line quotes
+
+export const Footer: FC<FooterProps> = (props) => {
+ const { uploadError, clearError, chatInputRef, submitDisabled } = props;
+
+ return (
+ <div className="w-full max-w-4xl">
+ {uploadError.show && <ErrorToast message={uploadError.message} onClose={clearError} />}
+ <ChatInput ref={chatInputRef} submitDisabled={submitDisabled} />
+ <WarningInfo infoMessage={CHAT_WARNING_INFO} />
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/header.tsx b/packages/app/src/react/features/ai-chat/components/header.tsx
new file mode 100644
index 00000000..1e31b7dd
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/header.tsx
@@ -0,0 +1,79 @@
+import { Tooltip } from 'flowbite-react';
+import { FC } from 'react';
+import { FaRegPenToSquare } from 'react-icons/fa6';
+import { Link } from 'react-router-dom';
+
+import { CloseIcon } from '@react/features/ai-chat/components/icons';
+import { DEFAULT_AVATAR_URL } from '@react/features/ai-chat/constants';
+import { useChatContext } from '@react/features/ai-chat/contexts';
+import { cn } from '@src/react/shared/utils/general';
+
+/**
+ * Skeleton component
+ */
+const Skeleton: FC<{ className?: string }> = ({ className }) => (
+ <div
+ className={cn(
+ 'bg-gradient-to-r from-gray-200 via-gray-300 to-gray-200 animate-pulse',
+ className,
+ )}
+ />
+);
+
+interface ChatHeaderProps {
+ avatar?: string;
+ agentName?: string;
+ isAgentLoading?: boolean;
+ isAvatarLoading?: boolean;
+}
+
+export const ChatHeader: FC<ChatHeaderProps> = (props) => {
+ const { avatar, agentName, isAgentLoading, isAvatarLoading } = props;
+ const { clearChatSession } = useChatContext();
+
+ return (
+ <div className="w-full bg-white border-b border-[#e5e5e5] h-14 flex justify-center absolute top-0 left-0 z-10 px-2.5 lg:px-0">
+ <div className="w-full max-w-4xl flex justify-between items-center">
+ {/* Left side - Avatar and Agent Name */}
+ <div className="flex items-center gap-3">
+ {isAvatarLoading ? (
+ <Skeleton className="size-8 rounded-full" />
+ ) : (
+ <img
+ src={avatar ?? DEFAULT_AVATAR_URL}
+ alt="avatar"
+ className="size-8 rounded-full transition-opacity duration-300 ease-in-out"
+ />
+ )}
+
+ <div className="flex items-center">
+ {isAgentLoading ? (
+ <Skeleton className="w-24 h-6 rounded-md" />
+ ) : (
+ <span className="text-lg font-medium text-[#111827] transition-opacity duration-300 ease-in-out">
+ {agentName || 'Unknown Agent'}
+ </span>
+ )}
+ </div>
+ </div>
+
+ {/* Right side - Action buttons */}
+ <div className="flex items-center justify-center gap-2">
+ <Tooltip content={<>New&nbsp;Chat</>} placement="bottom">
+ <button
+ className="cursor-pointer w-6 h-6 flex items-center justify-center"
+ onClick={clearChatSession}
+ >
+ <FaRegPenToSquare className="text-gray-500 w-4 h-4" />
+ </button>
+ </Tooltip>
+ <Tooltip content="Exit" placement="bottom">
+ <Link to="/agents">
+ <CloseIcon className="text-gray-500 w-6 h-6" />
+ </Link>
+ </Tooltip>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/icons.tsx b/packages/app/src/react/features/ai-chat/components/icons.tsx
index 3870aa65..16f755a5 100644
--- a/packages/app/src/react/features/ai-chat/components/icons.tsx
+++ b/packages/app/src/react/features/ai-chat/components/icons.tsx
@@ -2,11 +2,6 @@ import { cn } from '@react/shared/utils/general';
export const CloseIcon = ({ className }: { className?: string }) => (
<svg className={cn('size-6', className)} fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth="2"
- d="M6 18L18 6M6 6l12 12"
- ></path>
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
</svg>
);
diff --git a/packages/app/src/react/features/ai-chat/components/index.ts b/packages/app/src/react/features/ai-chat/components/index.ts
index 4abdc5e7..947556b3 100644
--- a/packages/app/src/react/features/ai-chat/components/index.ts
+++ b/packages/app/src/react/features/ai-chat/components/index.ts
@@ -1,14 +1,20 @@
export * from './attachment-button';
-export * from './chat-bubble';
-export * from './chat-container';
-export * from './chat-header';
-export * from './chat-history';
-export * from './code-block-with-copy-button';
+export * from './chat';
+export * from './chats';
+export * from './code-block';
+export * from './container';
+export * from './error-message';
export * from './error-toast';
export * from './file-item-preview';
-export * from './query-input';
+export * from './footer';
+export * from './header';
+export * from './markdown-renderer';
+export * from './input';
export * from './reply-loader';
export * from './scroll-to-bottom-button';
export * from './send-button';
+export * from './system-message';
export * from './thinking-message';
-export * from './warning-info-chat';
+export * from './typewriter';
+export * from './user-message';
+export * from './warning-info';
diff --git a/packages/app/src/react/features/ai-chat/components/query-input.tsx b/packages/app/src/react/features/ai-chat/components/input.tsx
similarity index 69%
rename from packages/app/src/react/features/ai-chat/components/query-input.tsx
rename to packages/app/src/react/features/ai-chat/components/input.tsx
index 36b50033..4ffd7067 100644
--- a/packages/app/src/react/features/ai-chat/components/query-input.tsx
+++ b/packages/app/src/react/features/ai-chat/components/input.tsx
@@ -1,5 +1,3 @@
-/* eslint-disable max-len */
-import classNames from 'classnames';
import {
ChangeEvent,
ClipboardEvent,
@@ -18,15 +16,19 @@ import { AttachmentButton, FileItemPreview, SendButton } from '@react/features/a
import { CHAT_ACCEPTED_FILE_TYPES } from '@react/features/ai-chat/constants';
import { useChatContext } from '@react/features/ai-chat/contexts';
import { createFileFromText } from '@react/features/ai-chat/utils';
+import {
+ forceScrollToBottomImmediate,
+ scrollManager,
+} from '@react/features/ai-chat/utils/scroll-utils';
import { MAX_CHAT_MESSAGE_LENGTH } from '@react/shared/constants';
+import { cn } from '@src/react/shared/utils/general';
-interface QueryInputProps extends PropsWithoutRef<JSX.IntrinsicElements['textarea']> {
- className?: string;
+interface ChatInputProps extends PropsWithoutRef<JSX.IntrinsicElements['textarea']> {
submitDisabled?: boolean;
maxLength?: number;
}
-export interface QueryInputRef {
+export interface ChatInputRef {
focus: () => void;
getValue: () => string;
setValue: (content: string) => void; // eslint-disable-line no-unused-vars
@@ -35,8 +37,8 @@ export interface QueryInputRef {
const TEXTAREA_MAX_HEIGHT = 160;
const LARGE_TEXT_THRESHOLD = 4000;
-export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
- ({ className, submitDisabled = false, maxLength = MAX_CHAT_MESSAGE_LENGTH }, ref) => {
+export const ChatInput = forwardRef<ChatInputRef, ChatInputProps>(
+ ({ submitDisabled = false, maxLength = MAX_CHAT_MESSAGE_LENGTH }, ref) => {
const {
files,
removeFile,
@@ -45,9 +47,9 @@ export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
isGenerating,
stopGenerating,
uploadingFiles,
- isQueryInputDisabled,
- queryInputPlaceholder,
- isQueryInputProcessing,
+ inputDisabled,
+ inputPlaceholder,
+ isInputProcessing,
handleFileDrop,
handleFileChange,
isMaxFilesUploaded,
@@ -98,17 +100,51 @@ export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
+ // Professional scroll to bottom after sending message
+ // Ensure scroll manager is initialized with the chat container
+ let chatContainer = document.querySelector('[data-chat-container]') as HTMLElement;
+
+ // Fallback: try to find container by class
+ if (!chatContainer) {
+ chatContainer = document.querySelector('.overflow-auto') as HTMLElement;
+ }
+
+ // Fallback: try to find container by scroll-smooth class
+ if (!chatContainer) {
+ chatContainer = document.querySelector('.scroll-smooth') as HTMLElement;
+ }
+
+ if (chatContainer) {
+ scrollManager.init(chatContainer);
+ } else {
+ // Try to use existing container if any
+ const existingContainer = scrollManager.getContainer();
+ if (!existingContainer) {
+ return; // No container available, skip scroll
+ }
+ }
+
+ // Reset cooldown to ensure user-initiated scrolls always work
+ scrollManager.resetForceScrollCooldown();
+
+ // Add a small delay to ensure the message is added to DOM first
+ setTimeout(() => {
+ forceScrollToBottomImmediate({
+ behavior: 'smooth',
+ delay: 0,
+ });
+ }, 150); // 150ms delay to ensure DOM is updated
}
- }, [message, files, sendMessage, isGenerating, stopGenerating, clearFiles]);
+ }, [message, files, isGenerating, inputDisabled]); // eslint-disable-line react-hooks/exhaustive-deps
const handleKeyDown = useCallback(
(e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
- handleSubmit();
+ !isGenerating && handleSubmit();
}
},
- [handleSubmit],
+ [handleSubmit, isGenerating],
);
const handleRemoveFile = useCallback(
@@ -131,16 +167,17 @@ export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
const handlePaste = (e: ClipboardEvent<HTMLTextAreaElement>) => {
e.preventDefault();
const pasted = e.clipboardData.getData('text/plain');
+ const text = message ? `${message} ${pasted}` : pasted;
if (pasted.length >= LARGE_TEXT_THRESHOLD) {
- const file = createFileFromText(pasted);
+ const file = createFileFromText(text);
handleFileDrop([file.file]);
setMessage('');
- } else setMessage((prev) => prev + pasted);
+ } else setMessage(text);
setTimeout(() => {
if (inputRef.current) {
inputRef.current.scrollTop = inputRef.current.scrollHeight;
inputRef.current.selectionStart = inputRef.current.selectionEnd =
- pasted.length >= LARGE_TEXT_THRESHOLD ? 0 : (message + pasted).length;
+ pasted.length >= LARGE_TEXT_THRESHOLD ? 0 : text.length;
}
}, 0);
};
@@ -153,15 +190,12 @@ export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
return (
<div
- className={classNames(
- 'bg-white border border-solid border-[#e5e5e5] rounded-lg min-h-[60px] py-1 text-sm flex flex-col items-center justify-center cursor-text',
- className,
- )}
+ className="w-full bg-white border border-solid border-[#e5e5e5] rounded-lg py-1 mt-2.5 text-sm flex flex-col items-start justify-center cursor-text"
onClick={handleContainerClick}
>
{files.length > 0 && (
<div
- className="flex flex-nowrap gap-2 w-full px-2.5 py-5 overflow-x-auto"
+ className="flex flex-nowrap gap-2 w-full h-full px-2.5 py-5 overflow-x-auto"
role="list"
aria-label="Attached files"
>
@@ -177,10 +211,7 @@ export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
)}
<div
- className={classNames(
- 'rounded-lg py-1 px-2.5 flex items-center text-sm w-full min-h-[60px] cursor-text',
- className,
- )}
+ className="rounded-lg py-1 px-2.5 flex items-center text-sm w-full min-h-[60px] cursor-text"
onClick={handleContainerClick}
>
<input
@@ -200,8 +231,7 @@ export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
onPaste={handlePaste}
onChange={handleChange}
onKeyDown={handleKeyDown}
- disabled={isQueryInputDisabled}
- placeholder={queryInputPlaceholder}
+ placeholder={inputPlaceholder}
maxLength={maxLength}
className="bg-white border-none outline-none ring-0 focus:outline-none focus:border-none flex-1 max-h-36 resize-none ph-no-capture text-[16px] font-[400] text-gray-900 placeholder:text-gray-500 placeholder:text-[16px] placeholder:font-[400]"
aria-label="Message input"
@@ -209,7 +239,7 @@ export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
/>
<div
- className={classNames(
+ className={cn(
'text-xs mr-2 w-[75px] text-right flex-shrink-0',
isMaxLengthReached ? 'text-red-500' : 'text-gray-500',
)}
@@ -223,7 +253,7 @@ export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
<AttachmentButton
onClick={handleAttachmentClick}
fileAttachmentDisabled={
- isMaxFilesUploaded || isQueryInputDisabled || isQueryInputProcessing || isGenerating
+ isMaxFilesUploaded || inputDisabled || isInputProcessing || isGenerating
}
isMaxFilesUploaded={isMaxFilesUploaded}
/>
@@ -231,7 +261,7 @@ export const QueryInput = forwardRef<QueryInputRef, QueryInputProps>(
<div onClick={(e) => e.stopPropagation()}>
<SendButton
- isProcessing={isQueryInputProcessing || isGenerating}
+ isProcessing={isInputProcessing || isGenerating}
disabled={!canSubmit}
onClick={handleSubmit}
/>
diff --git a/packages/app/src/react/features/ai-chat/components/markdown-renderer.tsx b/packages/app/src/react/features/ai-chat/components/markdown-renderer.tsx
new file mode 100644
index 00000000..8044d656
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/markdown-renderer.tsx
@@ -0,0 +1,74 @@
+import { FC } from 'react';
+import ReactMarkdown from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+
+import { CodeBlock } from '@react/features/ai-chat/components';
+import { cn } from '@src/react/shared/utils/general';
+
+interface IMarkdownRendererProps {
+ message: string;
+ className?: string;
+}
+
+/**
+ * Shared Markdown renderer component with consistent styling
+ * Used by both SystemMessage and Typewriter components
+ */
+export const MarkdownRenderer: FC<IMarkdownRendererProps> = ({ message, className }) => {
+ return (
+ <div className={className}>
+ <ReactMarkdown
+ children={message}
+ remarkPlugins={[remarkGfm]}
+ components={{
+ // Headers with consistent styling
+ h1: (props) => <h1 style={{ fontWeight: 'bold', fontSize: '2em' }} {...props} />,
+ h2: (props) => <h2 style={{ fontWeight: 'bold', fontSize: '1.5em' }} {...props} />,
+ h3: (props) => <h3 style={{ fontWeight: 'bold', fontSize: '1.17em' }} {...props} />,
+ h4: (props) => <h4 style={{ fontWeight: 'bold', fontSize: '1em' }} {...props} />,
+ h5: (props) => <h5 style={{ fontWeight: 'bold', fontSize: '0.83em' }} {...props} />,
+ h6: (props) => <h6 style={{ fontWeight: 'bold', fontSize: '0.67em' }} {...props} />,
+
+ // Code blocks and inline code
+ code({ className, children, ...props }) {
+ const match = /language-(\w+)/.exec(className || '');
+ const content = String(children).replace(/\n$/, '');
+
+ // Determine if content should be rendered as CodeBlock
+ const isCodeBlock =
+ match ||
+ content.includes('\n') ||
+ content.length > 50 ||
+ /[{}();=<>]/.test(content) ||
+ /^(function|class|import|export|const|let|var|if|for|while)/.test(content.trim());
+
+ return isCodeBlock ? (
+ <CodeBlock language={match?.[1] || 'text'}>{content}</CodeBlock>
+ ) : (
+ <code
+ className={cn(
+ 'bg-gray-100 text-gray-800 px-1.5 py-0.5 rounded text-sm font-mono border whitespace-pre-wrap text-wrap max-w-full',
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </code>
+ );
+ },
+
+ // Images with responsive styling
+ img: (props) => (
+ <img {...props} className="rounded-xl" style={{ maxWidth: '100%', height: 'auto' }} />
+ ),
+
+ // Links with security attributes
+ a: (props) => <a {...props} target="_blank" rel="noopener noreferrer" />,
+
+ // Paragraphs with proper whitespace handling
+ p: ({ children }) => <p className="whitespace-pre-wrap">{children}</p>,
+ }}
+ />
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/reply-loader.tsx b/packages/app/src/react/features/ai-chat/components/reply-loader.tsx
index f8e3a777..f82c7099 100644
--- a/packages/app/src/react/features/ai-chat/components/reply-loader.tsx
+++ b/packages/app/src/react/features/ai-chat/components/reply-loader.tsx
@@ -1,15 +1,5 @@
-import { FC } from 'react';
-
-interface ReplyLoaderProps {
- avatar?: string;
-}
-
-export const ReplyLoader: FC<ReplyLoaderProps> = ({ avatar }) => (
+export const ReplyLoader = () => (
<div className="flex items-center gap-2 pr-[100px]">
- {/* <img
- src={avatar ?? DEFAULT_AVATAR_URL}
- className="w-8 h-8 rounded-full bg-cover bg-center border border-[#dfdfdf] border-solid"
- /> */}
<div className="rounded-t-3xl rounded-br-3xl px-6 py-4">
<div className="chat-loader" />
</div>
diff --git a/packages/app/src/react/features/ai-chat/components/scroll-to-bottom-button.tsx b/packages/app/src/react/features/ai-chat/components/scroll-to-bottom-button.tsx
index 971d7306..c8bc0979 100644
--- a/packages/app/src/react/features/ai-chat/components/scroll-to-bottom-button.tsx
+++ b/packages/app/src/react/features/ai-chat/components/scroll-to-bottom-button.tsx
@@ -6,7 +6,7 @@ interface ScrollToBottomButtonProps {
}
export const ScrollToBottomButton: FC<ScrollToBottomButtonProps> = ({ onClick }) => (
- <div className="w-full flex justify-center items-center fixed bottom-32 md:bottom-28 z-10">
+ <div className="w-full max-w-4xl flex justify-center items-center fixed bottom-32 md:bottom-28 z-10">
<button
className="bg-white border border-solid border-black border-opacity-10 text-gray-900 rounded-full p-2 shadow-lg hover:bg-gray-50 transition-colors duration-200"
onClick={onClick}
diff --git a/packages/app/src/react/features/ai-chat/components/system-message.tsx b/packages/app/src/react/features/ai-chat/components/system-message.tsx
new file mode 100644
index 00000000..45669d80
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/system-message.tsx
@@ -0,0 +1,97 @@
+import { Tooltip } from 'flowbite-react';
+import { FC, useRef, useState } from 'react';
+import { FaCheck, FaRegCopy } from 'react-icons/fa6';
+
+import {
+ ErrorMessage,
+ MarkdownRenderer,
+ ThinkingMessage,
+ Typewriter,
+} from '@react/features/ai-chat/components';
+
+interface ISystemMessageBubble {
+ message: string;
+ avatar?: string;
+ isError?: boolean;
+ isRetrying?: boolean;
+ onRetryClick?: () => void;
+ thinkingMessage?: string;
+ typingAnimation?: boolean;
+ onTypingComplete?: () => void;
+ onTypingProgress?: () => void;
+}
+
+export const SystemMessage: FC<ISystemMessageBubble> = ({
+ avatar,
+ message,
+ isError,
+ isRetrying,
+ onRetryClick,
+ thinkingMessage,
+ onTypingComplete,
+ onTypingProgress,
+ typingAnimation = true,
+}) => {
+ const [copied, setCopied] = useState(false);
+ const contentRef = useRef<HTMLDivElement>(null);
+
+ const handleCopy = () => {
+ if (contentRef.current) {
+ const range = document.createRange();
+ range.selectNodeContents(contentRef.current);
+ const selection = window.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+
+ try {
+ document.execCommand('copy');
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ } catch (err) {
+ console.error('Failed to copy text: ', err); // eslint-disable-line no-console
+ }
+
+ selection?.removeAllRanges();
+ }
+ };
+
+ return (
+ <div className="system-message-bubble relative">
+ <div className="flex-1" ref={contentRef}>
+ {isError ? (
+ <ErrorMessage message={message} onRetryClick={onRetryClick} isRetrying={isRetrying} />
+ ) : (
+ <div className="chat-rich-text-response space-y-1 rounded-lg p-3 text-[#141414]">
+ {typingAnimation ? (
+ <Typewriter
+ message={message}
+ speed={2}
+ isTyping={typingAnimation}
+ onComplete={onTypingComplete}
+ onTypingProgress={onTypingProgress}
+ />
+ ) : (
+ <MarkdownRenderer message={message} />
+ )}
+
+ {/* Display thinking message inline if present */}
+ {thinkingMessage && <ThinkingMessage message={thinkingMessage} avatar={avatar} />}
+ </div>
+ )}
+ </div>
+
+ {!isError && !thinkingMessage && (
+ <div className="flex gap-4 p-4 pl-0">
+ <Tooltip content={copied ? 'Copied!' : 'Copy'} placement="bottom">
+ <button
+ onClick={handleCopy}
+ className="text-gray-500 hover:text-gray-700 transition-colors"
+ >
+ {copied ? <FaCheck /> : <FaRegCopy />}
+ </button>
+ </Tooltip>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/typewriter.tsx b/packages/app/src/react/features/ai-chat/components/typewriter.tsx
new file mode 100644
index 00000000..7f7a2069
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/typewriter.tsx
@@ -0,0 +1,175 @@
+import { FC, useCallback, useEffect, useState } from 'react';
+
+import { MarkdownRenderer } from '@react/features/ai-chat/components';
+import { forceScrollToBottom } from '@react/features/ai-chat/utils/scroll-utils';
+import { useChatContext } from '../contexts';
+
+interface ITypewriterProps {
+ message: string;
+ speed?: number;
+ onComplete?: () => void;
+ isTyping?: boolean;
+ minSpeed?: number;
+ maxSpeed?: number;
+ onTypingProgress?: () => void;
+}
+
+/**
+ * Typewriter component that displays text character by character with typing animation
+ * Similar to ChatGPT's typing effect
+ */
+export const Typewriter: FC<ITypewriterProps> = ({
+ message,
+ speed = 5,
+ onComplete,
+ isTyping = true,
+ minSpeed = 1,
+ maxSpeed = 20,
+ onTypingProgress,
+}) => {
+ const [displayedText, setDisplayedText] = useState('');
+ const [currentIndex, setCurrentIndex] = useState(0);
+ const [lastMessageLength, setLastMessageLength] = useState(0);
+ const { isGenerating = true } = useChatContext();
+
+ // Fast typewriter-effect library style speed
+ const getTypingSpeed = useCallback((char: string, messageLength: number): number => {
+ // Very fast base speed like typewriter-effect library
+ let baseSpeed = 20; // 20ms base speed (very fast)
+
+ // Character-specific speeds (minimal variation for smoothness)
+ if (char === ' ' || char === '\n') {
+ baseSpeed = 10; // Almost instant for spaces
+ } else if (/[a-zA-Z0-9]/.test(char)) {
+ baseSpeed = 15; // Very fast for letters/numbers
+ } else if (/[.,!?;:]/.test(char)) {
+ baseSpeed = 25; // Slight pause for punctuation
+ } else if (/[{}()[\]<>]/.test(char)) {
+ baseSpeed = 12; // Fast for brackets
+ } else if (char === '\t') {
+ baseSpeed = 8; // Very fast for tabs
+ } else if (/[#*`~]/.test(char)) {
+ baseSpeed = 18; // Fast for markdown
+ }
+
+ // Add tiny random variation for natural feel (like typewriter-effect)
+ const variation = (Math.random() - 0.5) * 8; // ±4ms variation
+ baseSpeed += variation;
+
+ // Slightly faster for longer messages (like typewriter-effect)
+ if (messageLength > 200) {
+ baseSpeed *= 0.8;
+ }
+ if (messageLength > 500) {
+ baseSpeed *= 0.7;
+ }
+ if (messageLength > 1000) {
+ baseSpeed *= 0.6;
+ }
+
+ return Math.max(5, baseSpeed); // Minimum 5ms for ultra-smoothness
+ }, []);
+
+ // Handle immediate display when generation is complete
+ useEffect(() => {
+ if (!isGenerating && message.length > 0) {
+ // When generation is complete, show all content immediately
+ setDisplayedText(message);
+ setCurrentIndex(message.length);
+
+ onComplete?.();
+ return;
+ }
+ }, [isGenerating, message, onComplete]);
+
+ // Separate effect for force scroll only when generation completes
+ useEffect(() => {
+ if (!isGenerating && message.length > 0) {
+ // Force scroll to bottom when message is fully generated (ignores user scroll position)
+
+ // Add a small delay to ensure the content is fully rendered
+ setTimeout(() => {
+ forceScrollToBottom({ behavior: 'smooth', delay: 0 });
+ }, 200);
+ }
+ }, [isGenerating]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ useEffect(() => {
+ if (!isTyping) {
+ setDisplayedText(message);
+ setCurrentIndex(message.length);
+ onComplete?.();
+ return;
+ }
+
+ // Skip animation only for very short messages (less than 3 characters) for instant display
+ if (message.length < 3) {
+ setDisplayedText(message);
+ setCurrentIndex(message.length);
+ onComplete?.();
+ return;
+ }
+
+ if (currentIndex < message.length) {
+ const currentChar = message[currentIndex];
+ const dynamicSpeed = getTypingSpeed(currentChar, message.length);
+
+ // Fast typewriter-effect style batching for smooth performance
+ let batchSize = 1;
+
+ // Smart batching based on message length (like typewriter-effect library)
+ if (message.length > 2000) {
+ batchSize = currentChar === ' ' || currentChar === '\n' ? 8 : 3;
+ } else if (message.length > 1000) {
+ batchSize = currentChar === ' ' || currentChar === '\n' ? 6 : 2;
+ } else if (message.length > 500) {
+ batchSize = currentChar === ' ' || currentChar === '\n' ? 4 : 2;
+ } else if (message.length > 200) {
+ batchSize = currentChar === ' ' || currentChar === '\n' ? 3 : 1;
+ } else {
+ batchSize = currentChar === ' ' || currentChar === '\n' ? 2 : 1;
+ }
+
+ const charsToAdd = message.slice(currentIndex, currentIndex + batchSize);
+
+ const timer = setTimeout(() => {
+ setDisplayedText((prevText) => prevText + charsToAdd);
+ setCurrentIndex((prevIndex) => prevIndex + batchSize);
+ // Trigger scroll during typing progress
+ onTypingProgress?.();
+ }, dynamicSpeed);
+
+ return () => clearTimeout(timer);
+ } else if (currentIndex >= message.length && displayedText.length === message.length) {
+ onComplete?.();
+ }
+ }, [
+ message,
+ speed,
+ currentIndex,
+ displayedText.length,
+ isTyping,
+ onComplete,
+ onTypingProgress,
+ minSpeed,
+ maxSpeed,
+ getTypingSpeed,
+ ]);
+
+ // Reset only when message length decreases (new message) or when message is empty
+ useEffect(() => {
+ if (message.length < lastMessageLength || message === '') {
+ setDisplayedText('');
+ setCurrentIndex(0);
+ setLastMessageLength(0);
+ } else if (message.length > lastMessageLength) {
+ setLastMessageLength(message.length);
+ }
+ }, [message, lastMessageLength]);
+
+ return (
+ <div className="typewriter-content type-writer-text type-writer-inner w-full text-wrap">
+ <MarkdownRenderer message={displayedText} />
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/user-message.tsx b/packages/app/src/react/features/ai-chat/components/user-message.tsx
new file mode 100644
index 00000000..8df39da7
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/components/user-message.tsx
@@ -0,0 +1,33 @@
+import { FileItemPreview } from '@react/features/ai-chat/components';
+import { FileWithMetadata } from '@react/shared/types/chat.types';
+import { FC } from 'react';
+
+interface IUserMessage {
+ message: string;
+ files?: FileWithMetadata[];
+}
+
+export const UserMessage: FC<IUserMessage> = ({ message, files }) => {
+ return (
+ <div className="break-all flex flex-col items-end">
+ {files && files.length > 0 && (
+ <div className="flex flex-nowrap gap-2 mb-2 overflow-x-auto">
+ {files.map((fileWithKey, index) => (
+ <FileItemPreview
+ isReadOnly
+ key={index}
+ file={fileWithKey}
+ fileKey={fileWithKey.metadata.key}
+ inChatBubble={true}
+ />
+ ))}
+ </div>
+ )}
+ {message && (
+ <div className="rounded-[18px] bg-[#f4f4f4] text-[#2b2b2b] p-3 px-4 w-fit whitespace-pre-wrap text-wrap max-w-[535px]">
+ {message}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/packages/app/src/react/features/ai-chat/components/warning-info-chat.tsx b/packages/app/src/react/features/ai-chat/components/warning-info.tsx
similarity index 57%
rename from packages/app/src/react/features/ai-chat/components/warning-info-chat.tsx
rename to packages/app/src/react/features/ai-chat/components/warning-info.tsx
index 2eb80220..a6b5b3cb 100644
--- a/packages/app/src/react/features/ai-chat/components/warning-info-chat.tsx
+++ b/packages/app/src/react/features/ai-chat/components/warning-info.tsx
@@ -5,7 +5,5 @@ interface WarningInfoProps {
}
export const WarningInfo: FC<WarningInfoProps> = ({ infoMessage }) => (
- <div className="py-4 flex justify-center">
- <span className="text-xs text-gray-500">{infoMessage}</span>
- </div>
+ <h6 className="py-4 text-center text-xs text-gray-500">{infoMessage}</h6>
);
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 8c6e3bb3..ee2a45ba 100644
--- a/packages/app/src/react/features/ai-chat/constants/index.ts
+++ b/packages/app/src/react/features/ai-chat/constants/index.ts
@@ -14,3 +14,6 @@ export const CHAT_ACCEPTED_FILE_TYPES = {
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 DEFAULT_AVATAR_URL =
+ 'https://gravatar.com/avatar/ccd5b19e810febbfd3d4321e27b15f77?s=400&d=mp&r=x';
diff --git a/packages/app/src/react/features/ai-chat/contexts/index.tsx b/packages/app/src/react/features/ai-chat/contexts/index.tsx
index 2830a149..3b3f58dd 100644
--- a/packages/app/src/react/features/ai-chat/contexts/index.tsx
+++ b/packages/app/src/react/features/ai-chat/contexts/index.tsx
@@ -1,4 +1,5 @@
-import { FileWithMetadata } from '@react/shared/types/chat.types';
+/* eslint-disable no-unused-vars */
+import { FileWithMetadata, IChatMessage } from '@react/shared/types/chat.types';
import { ChangeEvent, createContext, FC, PropsWithChildren, useContext } from 'react';
interface ChatContextType {
@@ -13,12 +14,12 @@ interface ChatContextType {
uploadError: { show: boolean; message: string };
clearError: () => void;
- isGenerating: boolean;
- isQueryInputProcessing: boolean;
isRetrying: boolean;
- chatHistoryMessages: any[];
- queryInputPlaceholder: string;
- isQueryInputDisabled: boolean;
+ isGenerating: boolean;
+ inputDisabled: boolean;
+ inputPlaceholder: string;
+ isInputProcessing: boolean;
+ messagesHistory: IChatMessage[];
sendMessage: (query: string, files?: FileWithMetadata[]) => void;
retryLastMessage: () => void;
@@ -32,6 +33,7 @@ const ChatContext = createContext<ChatContextType | undefined>(undefined);
* Hook to use the chat context
* @throws {Error} If used outside of ChatProvider
*/
+// eslint-disable-next-line react-refresh/only-export-components
export const useChatContext = () => {
const context = useContext(ChatContext);
if (!context) throw new Error('useChatContext must be used within a ChatProvider');
diff --git a/packages/app/src/react/features/ai-chat/hooks/agent-settings.ts b/packages/app/src/react/features/ai-chat/hooks/agent-settings.ts
index 15a37367..fd042a67 100644
--- a/packages/app/src/react/features/ai-chat/hooks/agent-settings.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/agent-settings.ts
@@ -9,6 +9,7 @@ const { data, error, isLoading, refetch, invalidate, setData } = useAgentSettin
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { deleteAgentSettings, updateAgentSettings } from '@react/features/ai-chat/clients';
+import { AgentSettings } from '@src/react/shared/types/agent-data.types';
export const useAgentSettings = (agentId: string) => {
const queryResult = useQuery({
@@ -23,7 +24,7 @@ export const useAgentSettings = (agentId: string) => {
{},
),
};
- }) as Promise<{ settings: { [key: string]: string } }>,
+ }) as Promise<{ settings: AgentSettings }>,
refetchInterval: false,
refetchOnWindowFocus: false,
refetchOnMount: false,
@@ -38,7 +39,7 @@ export const useUpdateAgentSettingsMutation = () => {
const queryClient = useQueryClient();
return useMutation(
- (params: { agentId: string; settings: { key: string; value: any } }) =>
+ (params: { agentId: string; settings: { key: string; value: string } }) =>
updateAgentSettings(params.agentId, params.settings),
{
onSuccess: (_, variables) => {
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 08dacc3f..e7502892 100644
--- a/packages/app/src/react/features/ai-chat/hooks/index.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/index.ts
@@ -1,5 +1,5 @@
export * from './agent-settings';
-export * from './aiagents';
+export * from './use-create-chat';
export * from './use-chat-actions';
export * from './use-chat-state';
export * from './use-chatbot-state';
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts b/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts
index 8d683bfe..1b8878fc 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-chat-actions.ts
@@ -12,9 +12,9 @@ interface UseChatActionsProps {
}
interface UseChatActionsReturn {
- chatHistoryMessages: IChatMessage[];
+ messagesHistory: IChatMessage[];
isGenerating: boolean;
- isQueryInputProcessing: boolean;
+ isInputProcessing: boolean;
isRetrying: boolean;
sendMessage: (message: string, attachedFiles?: FileWithMetadata[]) => Promise<void>; // eslint-disable-line no-unused-vars
retryLastMessage: () => void;
@@ -34,9 +34,9 @@ export const useChatActions = ({
avatar,
onChatComplete,
}: UseChatActionsProps): UseChatActionsReturn => {
- const [chatHistoryMessages, setChatHistoryMessages] = useState<IChatMessage[]>([]);
+ const [messagesHistory, setMessagesHistory] = useState<IChatMessage[]>([]);
const [isGenerating, setIsGenerating] = useState(false);
- const [isQueryInputProcessing, setIsQueryInputProcessing] = useState(false);
+ const [isInputProcessing, setIsInputProcessing] = useState(false);
const [isRetrying, setIsRetrying] = useState(false);
// Store both message and attached files for retry functionality
@@ -44,7 +44,7 @@ export const useChatActions = ({
const abortControllerRef = useRef<AbortController | null>(null);
const clearMessages = useCallback(() => {
- setChatHistoryMessages([]);
+ setMessagesHistory([]);
lastUserMessageRef.current = { message: '', attachedFiles: [] };
}, []);
@@ -54,7 +54,7 @@ export const useChatActions = ({
abortControllerRef.current = null;
}
setIsGenerating(false);
- setIsQueryInputProcessing(false);
+ setIsInputProcessing(false);
}, []);
const sendMessage = useCallback(
@@ -69,7 +69,7 @@ export const useChatActions = ({
// Add user message to chat history
if (message.trim()) {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
const newMessage: IChatMessage = {
me: true,
message: message.replace(/\n/g, '\n'),
@@ -79,13 +79,13 @@ export const useChatActions = ({
return [...prev, newMessage];
});
} else if (attachedFiles?.length) {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
const newMessage: IChatMessage = {
me: true,
message: '',
type: 'user',
files: attachedFiles,
- hideMessageBubble: true,
+ hideMessage: true,
};
return [...prev, newMessage];
});
@@ -100,10 +100,10 @@ export const useChatActions = ({
isReplying: true,
};
- setChatHistoryMessages((prev) => [...prev, replyMessage]);
+ setMessagesHistory((prev) => [...prev, replyMessage]);
try {
- setIsQueryInputProcessing(true);
+ setIsInputProcessing(true);
setIsGenerating(true);
abortControllerRef.current = new AbortController();
@@ -116,9 +116,8 @@ export const useChatActions = ({
chatId,
signal,
onResponse: (value: string, errorInfo?: { isError?: boolean; errorType?: string }) => {
- setChatHistoryMessages((bubbles) => {
- // Only remove thinking messages and clean message when we have actual content
- // This ensures debug messages are preserved until content starts arriving
+ setMessagesHistory((bubbles) => {
+ // Only remove thinking messages if we have actual content
if (value && value.trim() !== '') {
const filteredBubbles = bubbles.filter((msg) => msg.type !== 'thinking');
@@ -135,7 +134,7 @@ export const useChatActions = ({
updatedBubbles[lastSystemMessageIndex].message = value;
updatedBubbles[lastSystemMessageIndex].isReplying = false;
updatedBubbles[lastSystemMessageIndex].isError = errorInfo?.isError || false;
- updatedBubbles[lastSystemMessageIndex].hideMessageBubble = false; // Show the message bubble
+ updatedBubbles[lastSystemMessageIndex].hideMessage = false; // Show the message bubble
updatedBubbles[lastSystemMessageIndex].thinkingMessage = undefined; // Clear thinking message
return updatedBubbles;
}
@@ -147,7 +146,7 @@ export const useChatActions = ({
});
},
onThinking: (thinking) => {
- setChatHistoryMessages((bubbles) => {
+ setMessagesHistory((bubbles) => {
// Find the last system message index
const lastSystemIndex =
bubbles
@@ -167,7 +166,7 @@ export const useChatActions = ({
});
},
onStart: () => {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage && lastMessage.type === 'system') {
@@ -179,7 +178,7 @@ export const useChatActions = ({
});
},
onEnd: () => {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
// Remove thinking messages when response is complete
const filteredMessages = prev.filter((msg) => msg.type !== 'thinking');
const newMessages = [...filteredMessages];
@@ -205,7 +204,7 @@ export const useChatActions = ({
});
} catch (error) {
if (error.name === 'AbortError') {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage) {
@@ -215,7 +214,7 @@ export const useChatActions = ({
return newMessages;
});
} else {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage) {
@@ -227,7 +226,7 @@ export const useChatActions = ({
});
}
} finally {
- setIsQueryInputProcessing(false);
+ setIsInputProcessing(false);
setIsRetrying(false);
setIsGenerating(false);
}
@@ -241,10 +240,8 @@ export const useChatActions = ({
lastMessage.message ||
(lastMessage.attachedFiles && lastMessage.attachedFiles.length > 0)
) {
- setIsRetrying(true);
-
// Remove the last error message and replace it with a new AI response message
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
const newMessages = [...prev];
const lastMessageIndex = newMessages.length - 1;
@@ -266,7 +263,7 @@ export const useChatActions = ({
// Retry the API call without adding a new user message
const retryApiCall = async () => {
try {
- setIsQueryInputProcessing(true);
+ setIsInputProcessing(true);
setIsGenerating(true);
abortControllerRef.current = new AbortController();
@@ -281,7 +278,7 @@ export const useChatActions = ({
chatId,
signal,
onResponse: (value: string, errorInfo?: { isError?: boolean; errorType?: string }) => {
- setChatHistoryMessages((bubbles) => {
+ setMessagesHistory((bubbles) => {
// Only remove thinking messages if we have actual content
if (value && value.trim() !== '') {
const filteredBubbles = bubbles.filter((msg) => msg.type !== 'thinking');
@@ -299,7 +296,7 @@ export const useChatActions = ({
updatedBubbles[lastSystemMessageIndex].message = value;
updatedBubbles[lastSystemMessageIndex].isReplying = false;
updatedBubbles[lastSystemMessageIndex].isError = errorInfo?.isError || false;
- updatedBubbles[lastSystemMessageIndex].hideMessageBubble = false;
+ updatedBubbles[lastSystemMessageIndex].hideMessage = false;
return updatedBubbles;
}
return filteredBubbles;
@@ -310,7 +307,7 @@ export const useChatActions = ({
});
},
onThinking: (thinking) => {
- setChatHistoryMessages((bubbles) => {
+ setMessagesHistory((bubbles) => {
// Find the last system message index
const lastSystemIndex =
bubbles
@@ -342,7 +339,7 @@ export const useChatActions = ({
// Insert after the last system message
newBubbles.splice(lastSystemIndex + 1, 0, thinkingMessage);
// Hide the system message when thinking starts
- newBubbles[lastSystemIndex].hideMessageBubble = true;
+ newBubbles[lastSystemIndex].hideMessage = true;
newBubbles[lastSystemIndex].isReplying = false;
} else {
// Add at the end if no system message
@@ -354,7 +351,7 @@ export const useChatActions = ({
});
},
onStart: () => {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage && lastMessage.type === 'system') {
@@ -364,7 +361,7 @@ export const useChatActions = ({
});
},
onEnd: () => {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
// Remove thinking messages when response is complete
const filteredMessages = prev.filter((msg) => msg.type !== 'thinking');
const newMessages = [...filteredMessages];
@@ -382,7 +379,7 @@ export const useChatActions = ({
});
} catch (error) {
if (error.name === 'AbortError') {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage) {
@@ -392,7 +389,7 @@ export const useChatActions = ({
return newMessages;
});
} else {
- setChatHistoryMessages((prev) => {
+ setMessagesHistory((prev) => {
const newMessages = [...prev];
const lastMessage = newMessages[newMessages.length - 1];
if (lastMessage) {
@@ -404,20 +401,21 @@ export const useChatActions = ({
});
}
} finally {
- setIsQueryInputProcessing(false);
+ setIsInputProcessing(false);
setIsRetrying(false);
setIsGenerating(false);
}
};
retryApiCall();
+ setIsRetrying(false);
}
}, [agentId, chatId, avatar, onChatComplete]);
return {
- chatHistoryMessages,
+ messagesHistory,
isGenerating,
- isQueryInputProcessing,
+ isInputProcessing,
isRetrying,
sendMessage,
retryLastMessage,
diff --git a/packages/app/src/react/features/ai-chat/hooks/aiagents.ts b/packages/app/src/react/features/ai-chat/hooks/use-create-chat.ts
similarity index 52%
rename from packages/app/src/react/features/ai-chat/hooks/aiagents.ts
rename to packages/app/src/react/features/ai-chat/hooks/use-create-chat.ts
index 4135170b..6578c1ac 100644
--- a/packages/app/src/react/features/ai-chat/hooks/aiagents.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-create-chat.ts
@@ -1,7 +1,7 @@
import { useMutation } from '@tanstack/react-query';
-import { createChat, fetchChatMessages } from '@react/features/ai-chat/clients';
-import { queryClient, useCustomSuspenseQuery } from '@react/shared/query-client';
+import { createChat } from '@react/features/ai-chat/clients';
+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';
@@ -14,23 +14,8 @@ export const agentRequestKeys = {
CONVERSATION_QUERY: ['get', '/api/page/chat/messages'],
};
-export const useChatMessagesSuspendedQuery = (
- params: { agentId: string; chatId: string; page: number; limit: number },
- opts: { enabled: boolean; suspense?: boolean; retry?: boolean } = {
- enabled: true,
- suspense: true,
- retry: false,
- },
-) => {
- return useCustomSuspenseQuery<any, Error>(
- [...agentRequestKeys.CONVERSATION_QUERY, params],
- () => fetchChatMessages(params),
- { enabled: opts.enabled, suspense: opts.suspense, retry: opts.retry },
- );
-};
-
-export const useCreateChatMutation = () => {
- return useMutation<CreateChatsResponse, Error, CreateChatRequest>(
+export const useCreateChatMutation = () =>
+ useMutation<CreateChatsResponse, Error, CreateChatRequest>(
agentRequestKeys.CHAT_CREATE_MUTATION,
(params) => createChat(params),
{
@@ -39,4 +24,3 @@ export const useCreateChatMutation = () => {
},
},
);
-};
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.ts b/packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.ts
index 36d813a0..8d5dc6f9 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.ts
+++ b/packages/app/src/react/features/ai-chat/hooks/use-scroll-to-bottom.ts
@@ -1,38 +1,73 @@
import { RefObject, useCallback, useEffect, useState } from 'react';
-export const useScrollToBottom = (containerRef: RefObject<HTMLElement>) => {
+import { scrollManager } from '@react/features/ai-chat/utils/scroll-utils';
+
+export const useScrollToBottom = (ref: RefObject<HTMLElement>) => {
const [showScrollButton, setShowScrollButton] = useState(false);
+ const [shouldAutoScroll, setShouldAutoScroll] = useState(true);
+
+ // Initialize scroll manager with container
+ useEffect(() => {
+ if (ref.current) {
+ scrollManager.init(ref.current);
+ }
+ }, [ref]);
const handleScroll = useCallback(() => {
const selection = window.getSelection();
if (selection && selection.toString().length > 0) return;
- if (containerRef.current) {
- const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
+ if (ref.current) {
+ const { scrollTop, scrollHeight, clientHeight } = ref.current;
const isScrolledUp = scrollHeight - scrollTop > clientHeight + 100; // 100px threshold
setShowScrollButton(isScrolledUp);
+
+ // Update auto-scroll state based on scroll position
+ const isNearBottom = scrollHeight - scrollTop <= clientHeight + 100;
+ setShouldAutoScroll(isNearBottom);
}
- }, [containerRef]);
+ }, [ref]);
const scrollToBottom = useCallback(
(smooth: boolean = true) => {
- if (containerRef.current) {
- containerRef.current.scrollTo({
- top: containerRef.current.scrollHeight,
+ if (ref.current) {
+ ref.current.scrollTo({
+ top: ref.current.scrollHeight,
behavior: smooth ? 'smooth' : 'auto',
});
+ // When user manually scrolls to bottom, enable auto-scroll
+ setShouldAutoScroll(true);
}
},
- [containerRef],
+ [ref],
+ );
+
+ // Professional smart scroll function
+ const smartScrollToBottom = useCallback(
+ (smooth: boolean = true) => {
+ if (!shouldAutoScroll) return;
+
+ // Use professional scroll manager
+ scrollManager.smartScrollToBottom({ behavior: smooth ? 'smooth' : 'auto', delay: 0 });
+ },
+ [shouldAutoScroll],
);
useEffect(() => {
- const container = containerRef.current;
+ const container = ref.current;
if (container) {
container.addEventListener('scroll', handleScroll);
return () => container.removeEventListener('scroll', handleScroll);
}
- }, [containerRef, handleScroll]);
+ }, [ref, handleScroll]);
- return { showScrollButton, handleScroll, scrollToBottom, setShowScrollButton };
+ return {
+ showScrollButton,
+ handleScroll,
+ scrollToBottom,
+ setShowScrollButton,
+ shouldAutoScroll,
+ smartScrollToBottom,
+ setShouldAutoScroll,
+ };
};
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.tsx
index 7727ef2a..3445aeb6 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
@@ -1,22 +1,18 @@
-import { FC, MutableRefObject, RefObject, useCallback, useEffect, useRef } from 'react';
+import { useCallback, useEffect, useRef } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
- ChatContainer,
ChatHeader,
- ChatHistory,
- ErrorToast,
- QueryInput,
- QueryInputRef,
- ScrollToBottomButton,
- WarningInfo,
+ ChatInputRef,
+ Chats,
+ Container,
+ Footer,
} from '@react/features/ai-chat/components';
import { ChatProvider } from '@react/features/ai-chat/contexts';
import {
useAgentSettings,
useChatActions,
useCreateChatMutation,
- useDragAndDrop,
useFileUpload,
useScrollToBottom,
useUpdateAgentSettingsMutation,
@@ -26,55 +22,30 @@ import { useAgent } from '@react/shared/hooks/agent';
import { EVENTS } from '@shared/posthog/constants/events';
import { Analytics } from '@shared/posthog/services/analytics';
-const CHAT_WARNING_INFO =
- "SmythOS can make mistakes, always check your work. We don't store chat history, save important work."; // eslint-disable-line quotes
-
-interface AIChatProps {
- givenAgent?: string;
- isMenuVisible?: boolean;
- isWarningVisible?: boolean;
-}
-
-/**
- * Combines multiple refs into a single ref callback
- */
-const combineRefs = <T extends HTMLElement>(
- ...refs: Array<RefObject<T> | MutableRefObject<T | null>>
-) => {
- return (element: T | null) => {
- refs.forEach((ref) => {
- if (!ref) return;
- (ref as MutableRefObject<T | null>).current = element;
- });
- };
-};
-
-const AIChat: FC<AIChatProps> = ({
- givenAgent,
- isMenuVisible = false,
- isWarningVisible = false,
-}) => {
+const AIChat = () => {
const params = useParams<{ agentId: string }>();
- const agentId = givenAgent || params?.agentId;
- const queryInputRef = useRef<QueryInputRef>(null);
+ const agentId = params?.agentId;
+ const chatInputRef = useRef<ChatInputRef>(null);
const chatContainerRef = useRef<HTMLDivElement>(null);
const isFirstMessageSentRef = useRef(false);
const navigate = useNavigate();
// API Hooks - optimized with minimal dependencies
- const { data: currentAgent, isLoading: isAgentLoading } = useAgent(agentId || '', {
+ const { data: agent, isLoading: isAgentLoading } = useAgent(agentId || '', {
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: false,
onError: () => navigate('/error/403'),
});
- const { data: agentSettingsData } = useAgentSettings(agentId || '');
+ const { data: settingsData, isLoading: isAgentSettingsLoading } = useAgentSettings(agentId || '');
const { mutateAsync: createChat, isPending: isChatCreating } = useCreateChatMutation();
const { mutateAsync: updateAgentSettings } = useUpdateAgentSettingsMutation();
+ const agentSettings = settingsData?.settings;
+
// Custom Hooks - optimized
- const { showScrollButton, handleScroll, scrollToBottom, setShowScrollButton } =
+ const { setShowScrollButton, smartScrollToBottom, ...scroll } =
useScrollToBottom(chatContainerRef);
const {
@@ -89,12 +60,10 @@ const AIChat: FC<AIChatProps> = ({
clearFiles,
} = useFileUpload();
- const dropzoneRef = useDragAndDrop({ onDrop: handleFileDrop });
-
const {
- chatHistoryMessages,
+ messagesHistory,
isGenerating,
- isQueryInputProcessing,
+ isInputProcessing,
isRetrying,
sendMessage,
retryLastMessage,
@@ -102,8 +71,8 @@ const AIChat: FC<AIChatProps> = ({
clearMessages,
} = useChatActions({
agentId: agentId || '',
- chatId: agentSettingsData?.settings?.lastConversationId,
- avatar: currentAgent?.aiAgentSettings?.avatar,
+ chatId: agentSettings?.lastConversationId,
+ avatar: agent?.aiAgentSettings?.avatar,
onChatComplete: () => {
if (!isFirstMessageSentRef.current) {
isFirstMessageSentRef.current = true;
@@ -112,8 +81,8 @@ const AIChat: FC<AIChatProps> = ({
});
// Fast memoized values - minimal dependencies
- const isQueryInputDisabled = isChatCreating || isAgentLoading || isQueryInputProcessing;
- const queryInputPlaceholder = currentAgent ? `Message ${currentAgent?.name}...` : 'Message ...';
+ const inputDisabled = isChatCreating || isAgentLoading || isInputProcessing;
+ const queryInputPlaceholder = agent ? `Message ${agent?.name}...` : 'Message ...';
const isMaxFilesUploaded = files.length >= FILE_LIMITS.MAX_ATTACHED_FILES;
// Fast callbacks - minimal dependencies
@@ -144,29 +113,25 @@ const AIChat: FC<AIChatProps> = ({
isFirstMessageSentRef.current = false;
clearMessages();
await createNewChatSession();
- queryInputRef.current?.focus();
+ chatInputRef.current?.focus();
Analytics.track(EVENTS.CHAT_EVENTS.SESSION_END);
Analytics.track(EVENTS.CHAT_EVENTS.SESSION_START);
}, [createNewChatSession, clearMessages, stopGenerating, setShowScrollButton]);
useEffect(() => {
- if (agentSettingsData?.settings && currentAgent) {
- currentAgent.aiAgentSettings = agentSettingsData.settings;
- currentAgent.id = agentId;
+ if (agentSettings && agent) {
+ agent.aiAgentSettings = agentSettings;
+ agent.id = agentId;
- if (!currentAgent?.aiAgentSettings?.lastConversationId) {
+ if (!agent?.aiAgentSettings?.lastConversationId) {
createNewChatSession();
}
}
- }, [agentSettingsData, currentAgent, agentId, createNewChatSession]);
-
- useEffect(() => {
- if (!isAgentLoading && !isQueryInputDisabled) queryInputRef.current?.focus();
- }, [isAgentLoading, isQueryInputDisabled]);
+ }, [agentSettings, agent, agentId, createNewChatSession]);
useEffect(() => {
- scrollToBottom();
- }, [chatHistoryMessages, scrollToBottom]);
+ if (!isAgentLoading && !inputDisabled) chatInputRef.current?.focus();
+ }, [isAgentLoading, inputDisabled]);
useEffect(() => {
Analytics.track(EVENTS.CHAT_EVENTS.SESSION_START);
@@ -189,11 +154,11 @@ const AIChat: FC<AIChatProps> = ({
// Chat state
isGenerating,
- isQueryInputProcessing,
+ isInputProcessing,
isRetrying,
- chatHistoryMessages,
- queryInputPlaceholder,
- isQueryInputDisabled,
+ messagesHistory,
+ inputPlaceholder: queryInputPlaceholder,
+ inputDisabled,
// Chat actions
sendMessage,
@@ -204,43 +169,29 @@ const AIChat: FC<AIChatProps> = ({
return (
<ChatProvider value={chatContextValue}>
- <div className="w-full h-full max-h-screen bg-white">
- {!isMenuVisible && (
- <ChatHeader
- agentName={currentAgent?.name || '...'}
- avatar={agentSettingsData?.settings?.avatar}
- />
- )}
-
- <ChatContainer>
- <div
- className="w-full h-full flex justify-center overflow-auto relative scroll-smooth"
- ref={combineRefs(chatContainerRef, dropzoneRef)}
- onScroll={handleScroll}
- >
- <div className="w-full pt-16 max-w-4xl mt-0">
- <ChatHistory
- agent={currentAgent}
- chatId={agentSettingsData?.settings?.lastConversationId || ''}
- messages={chatHistoryMessages}
- />
- </div>
- {showScrollButton && <ScrollToBottomButton onClick={() => scrollToBottom(true)} />}
- </div>
- {uploadError.show && (
- <div className="w-full max-w-4xl">
- <ErrorToast message={uploadError.message} onClose={clearError} />
- </div>
- )}
- <div className="w-full max-w-4xl mt-[10px]">
- <QueryInput
- ref={queryInputRef}
- submitDisabled={isChatCreating || isAgentLoading || uploadingFiles.size > 0}
- />
- {!isWarningVisible && <WarningInfo infoMessage={CHAT_WARNING_INFO} />}
- </div>
- </ChatContainer>
- </div>
+ <Container>
+ <ChatHeader
+ agentName={agent?.name}
+ avatar={agentSettings?.avatar}
+ isAgentLoading={isAgentLoading}
+ isAvatarLoading={isAgentSettingsLoading}
+ />
+
+ <Chats
+ {...scroll}
+ agent={agent}
+ messages={messagesHistory}
+ containerRef={chatContainerRef}
+ handleFileDrop={handleFileDrop}
+ smartScrollToBottom={smartScrollToBottom}
+ />
+ <Footer
+ uploadError={uploadError}
+ clearError={clearError}
+ chatInputRef={chatInputRef}
+ submitDisabled={isChatCreating || isAgentLoading || uploadingFiles.size > 0}
+ />
+ </Container>
</ChatProvider>
);
};
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 25397731..9e97dc7e 100644
--- a/packages/app/src/react/features/ai-chat/utils/index.ts
+++ b/packages/app/src/react/features/ai-chat/utils/index.ts
@@ -174,18 +174,48 @@ export const chatUtils = {
: `https://${agentId}.${remoteDomain}`;
},
splitDataToJSONObjects: (data: string) => {
- const jsonStrings = data.split('}{').map((str, index, array) => {
- if (index !== 0) str = '{' + str;
- if (index !== array.length - 1) str += '}';
- return str;
- });
+ // 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) {
- console.error('Error parsing JSON:', error); // eslint-disable-line no-console
+ // Silently skip invalid JSON instead of logging errors
return null;
}
})
@@ -268,6 +298,7 @@ export const chatUtils = {
const decodedValue = new TextDecoder().decode(value);
accumulatedData += decodedValue;
+ // Only process if we have complete JSON objects
const jsonObjects: ResponseFormat[] = chatUtils.splitDataToJSONObjects(accumulatedData);
// First pass: Check for state transitions
@@ -379,7 +410,11 @@ export const chatUtils = {
// Handle final content transition - only when we're actually getting content
if (messageState === ('debug' as MessageState)) {
handleMessageTransition('final');
- message += message.length > 0 ? '\n' + jsonObject.content : jsonObject.content; // Final response will begin below previous message
+ // Safely concatenate content without causing JSON parsing issues
+ const content = jsonObject.content || '';
+ if (content) {
+ message += message.length > 0 ? '\n' + content : content;
+ }
}
// Stop all thinking messages when content starts arriving
@@ -405,7 +440,10 @@ export const chatUtils = {
}
// Clear accumulated data after processing all JSON objects
- accumulatedData = '';
+ // Only clear if we successfully processed some objects
+ if (jsonObjects.length > 0) {
+ accumulatedData = '';
+ }
}
} catch (error) {
if (error.name === 'AbortError') {
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.ts
new file mode 100644
index 00000000..16fbf2c3
--- /dev/null
+++ b/packages/app/src/react/features/ai-chat/utils/scroll-utils.ts
@@ -0,0 +1,260 @@
+/**
+ * Professional scroll utilities for chat interface
+ * Provides smooth, performant, and reliable scrolling behavior
+ */
+
+interface ScrollOptions {
+ behavior?: 'smooth' | 'auto' | 'instant';
+ block?: 'start' | 'center' | 'end' | 'nearest';
+ inline?: 'start' | 'center' | 'end' | 'nearest';
+}
+
+interface ScrollToBottomOptions extends ScrollOptions {
+ force?: boolean;
+ delay?: number;
+}
+
+/**
+ * Professional scroll-to-bottom utility with multiple strategies
+ */
+export class ScrollManager {
+ private static instance: ScrollManager;
+ private scrollContainer: HTMLElement | null = null;
+ private isScrolling = false;
+ private scrollTimeout: number | null = null;
+ private lastForceScrollTime = 0;
+
+ static getInstance(): ScrollManager {
+ if (!ScrollManager.instance) {
+ ScrollManager.instance = new ScrollManager();
+ }
+ return ScrollManager.instance;
+ }
+
+ /**
+ * Initialize scroll manager with container element
+ */
+ init(container: HTMLElement | null): void {
+ this.scrollContainer = container;
+ }
+
+ /**
+ * Get the current scroll container
+ */
+ getContainer(): HTMLElement | null {
+ return this.scrollContainer || this.findScrollContainer();
+ }
+
+ /**
+ * Find scroll container automatically
+ */
+ private findScrollContainer(): HTMLElement | null {
+ const selectors = [
+ '.overflow-auto',
+ '[data-chat-container]',
+ '.scroll-smooth',
+ '[class*="overflow"]',
+ ];
+
+ for (const selector of selectors) {
+ const element = document.querySelector(selector) as HTMLElement;
+ if (element) return element;
+ }
+
+ return null;
+ }
+
+ /**
+ * Check if user is near bottom of scroll container
+ */
+ isNearBottom(threshold: number = 100): boolean {
+ const container = this.getContainer();
+ if (!container) return true;
+
+ const { scrollTop, scrollHeight, clientHeight } = container;
+ return scrollHeight - scrollTop <= clientHeight + 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
+ */
+ scrollToBottom(options: ScrollToBottomOptions = {}): Promise<void> {
+ return new Promise((resolve) => {
+ const { behavior = 'smooth', force = false, delay = 0 } = options;
+
+ // Prevent too frequent force scrolls (reduced cooldown for better UX)
+ if (force) {
+ const now = Date.now();
+ if (now - this.lastForceScrollTime < 100) {
+ // 100ms cooldown (reduced from 500ms)
+ resolve();
+ return;
+ }
+ this.lastForceScrollTime = now;
+ }
+
+ // Clear any existing scroll timeout
+ if (this.scrollTimeout) {
+ clearTimeout(this.scrollTimeout);
+ }
+
+ const performScroll = () => {
+ const container = this.getContainer();
+
+ if (!container) {
+ resolve();
+ return;
+ }
+
+ // Don't scroll if user is scrolled up and force is false
+ if (!force && !this.isNearBottom()) {
+ resolve();
+ return;
+ }
+
+ this.isScrolling = true;
+
+ // Use modern scrollTo API with smooth behavior
+ container.scrollTo({
+ top: container.scrollHeight,
+ behavior: behavior === 'instant' ? 'auto' : behavior,
+ });
+
+ // Reset scrolling flag after animation
+ if (behavior === 'smooth') {
+ this.scrollTimeout = window.setTimeout(() => {
+ this.isScrolling = false;
+ resolve();
+ }, 300); // Typical smooth scroll duration
+ } else {
+ this.isScrolling = false;
+ resolve();
+ }
+ };
+
+ if (delay > 0) {
+ this.scrollTimeout = window.setTimeout(performScroll, delay);
+ } else {
+ // Use requestAnimationFrame for better performance
+ requestAnimationFrame(performScroll);
+ }
+ });
+ }
+
+ /**
+ * 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)
+ */
+ forceScrollToBottomImmediate(options: ScrollToBottomOptions = {}): Promise<void> {
+ const originalCooldown = this.lastForceScrollTime;
+ this.lastForceScrollTime = 0; // Reset cooldown
+
+ // Explicitly set force to true and ensure it's not overridden
+ const forceOptions: ScrollToBottomOptions = {
+ ...options,
+ force: true,
+ };
+
+ return this.scrollToBottom(forceOptions).finally(() => {
+ this.lastForceScrollTime = originalCooldown; // Restore original cooldown
+ });
+ }
+
+ /**
+ * Smart scroll that respects user's scroll position
+ */
+ smartScrollToBottom(options: ScrollToBottomOptions = {}): Promise<void> {
+ 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
+export const scrollManager = ScrollManager.getInstance();
+
+// Convenience functions
+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/shared/hooks/agent.ts b/packages/app/src/react/shared/hooks/agent.ts
index 9276485d..e39a5106 100644
--- a/packages/app/src/react/shared/hooks/agent.ts
+++ b/packages/app/src/react/shared/hooks/agent.ts
@@ -6,21 +6,10 @@ const { data, error, isLoading, refetch, invalidate, setData } = useAgent(agent
});
*/
-import { Agent } from '@react/shared/types/agent-data.types';
+import { AgentDetails } from '@react/shared/types/agent-data.types';
import { useQuery, useQueryClient } from '@tanstack/react-query';
-interface AgentResponse {
- success: boolean;
- agent: Agent;
-}
-
-interface CreateAgentResponse {
- id: string;
- name: string;
- success: boolean;
-}
-
-const getAgent = async (agentId: string) => {
+const getAgent = async (agentId: string): Promise<AgentDetails> => {
const res = await fetch(`/api/agent/${agentId}`);
if (!res.ok) {
throw new Error('Network response was not ok');
@@ -55,55 +44,3 @@ export const useAgent = (agentId: string, options = {}) => {
setData,
};
};
-
-export const useAgentMutations = () => {
- const queryClient = useQueryClient();
-
- const createAgent = async (agentData: {
- name: string;
- behavior?: string;
- description?: string;
- domain?: string[];
- data?: any;
- }): Promise<CreateAgentResponse> => {
- const response = await fetch('/api/agent', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(agentData),
- });
-
- if (!response.ok) {
- throw new Error('Failed to create agent');
- }
-
- const data = await response.json();
- await queryClient.invalidateQueries(['agents']); // Invalidate agents list
- return data;
- };
-
- const saveAgent = async (agentId: string, agentData: Partial<Agent>): Promise<AgentResponse> => {
- const response = await fetch(`/api/agent/${agentId}`, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(agentData),
- });
-
- if (!response.ok) {
- throw new Error('Failed to save agent');
- }
-
- const data = await response.json();
- await queryClient.invalidateQueries(['agent_data', agentId]); // Invalidate specific agent data
- await queryClient.invalidateQueries(['agents']); // Invalidate agents list
- return data.agent;
- };
-
- return {
- createAgent,
- saveAgent,
- };
-};
diff --git a/packages/app/src/react/shared/types/agent-data.types.ts b/packages/app/src/react/shared/types/agent-data.types.ts
index 7d002c08..509157ff 100644
--- a/packages/app/src/react/shared/types/agent-data.types.ts
+++ b/packages/app/src/react/shared/types/agent-data.types.ts
@@ -1,3 +1,33 @@
+export interface AgentSettings {
+ id: number;
+ key: string;
+ value: string;
+ avatar: string;
+ chatGptModel: string;
+ lastConversationId: string;
+ aiAgentId: string;
+ createdAt: string;
+ updatedAt: string;
+}
+interface Domain {
+ name: string;
+}
+interface Connection {
+ sourceId: string;
+ sourceIndex: number;
+ targetId: string;
+ targetIndex: number;
+}
+export interface AgentData {
+ version: string;
+ components: Component[];
+ connections: Connection[];
+ description: string;
+ behavior?: string;
+ debugSessionEnabled: boolean;
+ shortDescription: string;
+ ui: { panzoom: { currentPan: { x: number; y: number }; currentZoom: number } };
+}
export interface Agent {
id: string;
name?: string;
@@ -24,7 +54,7 @@ export interface Agent {
data?: {
version: string;
components: Component[];
- connections: any[];
+ connections: Connection[];
description: string;
behavior?: string;
debugSessionEnabled: boolean;
@@ -39,15 +69,8 @@ export interface Agent {
};
};
};
- aiAgentSettings?: {
- id: number;
- key: string;
- value: string;
- aiAgentId: string;
- createdAt: string;
- updatedAt: string;
- }[];
- domain?: any[];
+ aiAgentSettings?: AgentSettings[];
+ domain?: Domain[];
isLocked?: boolean;
_count?: {
AiAgentDeployment: number;
@@ -120,16 +143,14 @@ export interface AgentDetails {
id: string;
name: string;
description: string;
- aiAgentSettings: any; // Define more specific type if possible
+ aiAgentSettings: AgentSettings;
contributors: Contributor[];
createdAt: string;
updatedAt: string;
changeActivity: ChangeActivity[];
- domain: any[]; // more specific please
+ domain: Domain[];
lockAt: string;
- _count: {
- AiAgentDeployment: number;
- };
+ _count: { AiAgentDeployment: number };
isLocked: boolean;
}
diff --git a/packages/app/src/react/shared/types/chat.types.ts b/packages/app/src/react/shared/types/chat.types.ts
index daf7ec51..8b14b5e8 100644
--- a/packages/app/src/react/shared/types/chat.types.ts
+++ b/packages/app/src/react/shared/types/chat.types.ts
@@ -21,7 +21,7 @@ export interface IChatMessage {
isError?: boolean;
isFirstMessage?: boolean;
files?: FileWithMetadata[];
- hideMessageBubble?: boolean;
+ hideMessage?: boolean;
thinkingMessage?: string; // Inline thinking message to show with system messages
isLast?: boolean; // Whether this is the last message in the chat
isRetrying?: boolean; // Whether this message is being retried