Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

Refactor Chat Context and Header for Enhanced State Management

Salman-Ahamed42eb9640dd5e
diff --git a/packages/app/src/react/features/ai-chat/components/header.tsx b/packages/app/src/react/features/ai-chat/components/header.tsx
index 3f4123b1..a6e1b75c 100644
--- a/packages/app/src/react/features/ai-chat/components/header.tsx
+++ b/packages/app/src/react/features/ai-chat/components/header.tsx
@@ -71,6 +71,8 @@ const fetchModelAgents = async (): Promise<ModelAgent[]> => {
export const ChatHeader: FC<ChatHeaderProps> = (props) => {
const { agent, isLoading, agentSettings } = props;
+ // const {} = useChatStores() || {};
+
const avatar = agentSettings?.avatar;
const selectedModel = agentSettings?.chatGptModel;
diff --git a/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx b/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx
index 27e67b44..79d7cb5d 100644
--- a/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx
+++ b/packages/app/src/react/features/ai-chat/contexts/chat-context.tsx
@@ -6,7 +6,11 @@ import { createContext, MutableRefObject } from 'react';
export interface IChatContext {
ref: { input?: MutableRefObject<ChatInputRef>; container?: MutableRefObject<HTMLDivElement> };
- agent: { data?: AgentDetails; settings?: AgentSettings; loading: boolean };
+ agent: {
+ data?: AgentDetails;
+ settings?: AgentSettings;
+ isLoading: { agent: boolean; settings: boolean };
+ };
files: {
isLoading: boolean;
errorMessage: string;
@@ -16,15 +20,18 @@ export interface IChatContext {
};
chat: {
// State
+ isChatCreating: boolean;
messages: IChatMessage[];
isStreaming: boolean;
isProcessing: boolean;
// Actions
+ createSession: () => Promise<void>;
sendMessage: (message: string, files?: File[] | IMessageFile[]) => Promise<void>;
retryMessage: () => Promise<void>;
stopGenerating: () => void;
clearMessages: () => void;
+ resetSession: () => Promise<void>;
};
// Model override (temporary, not saved to agent config)
modelOverride: string | null;
@@ -33,7 +40,7 @@ export interface IChatContext {
export const ChatContext = createContext<IChatContext>({
ref: { input: undefined, container: undefined },
- agent: { data: undefined, settings: undefined, loading: false },
+ agent: { data: undefined, settings: undefined, isLoading: { agent: false, settings: false } },
files: {
data: [],
isLoading: false,
@@ -42,13 +49,16 @@ export const ChatContext = createContext<IChatContext>({
removeFile: async () => {},
},
chat: {
+ isChatCreating: false,
messages: [],
isStreaming: false,
isProcessing: false,
+ createSession: async () => {},
sendMessage: async () => {},
retryMessage: async () => {},
stopGenerating: () => {},
clearMessages: () => {},
+ resetSession: async () => {},
},
modelOverride: null,
setModelOverride: () => {},
diff --git a/packages/app/src/react/features/ai-chat/contexts/index.new.tsx b/packages/app/src/react/features/ai-chat/contexts/index.new.tsx
index 0004b53d..72d163e8 100644
--- a/packages/app/src/react/features/ai-chat/contexts/index.new.tsx
+++ b/packages/app/src/react/features/ai-chat/contexts/index.new.tsx
@@ -1,10 +1,16 @@
import { ChatInputRef } from '@react/features/ai-chat/components/input';
import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat-context';
-import { useAgent } from '@src/react/shared/hooks/agent';
-import { FC, ReactNode, useMemo, useRef, useState } from 'react';
+import {
+ useAgentSettings,
+ useAttachments,
+ useCreateChatMutation,
+ useUpdateAgentSettingsMutation,
+} from '@react/features/ai-chat/hooks';
+import { useAgent } from '@react/shared/hooks/agent';
+import { Observability } from '@shared/observability';
+import { EVENTS } from '@shared/posthog/constants/events';
+import { FC, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
-import { useAgentSettings } from '../hooks/agent-settings';
-import { useAttachments } from '../hooks/use-attachments';
import { useChat } from '../hooks/use-chat';
interface IProps {
@@ -22,6 +28,7 @@ export const ChatContextProvider: FC<IProps> = ({ children }) => {
// Internal refs for tracking state
const isFirstMessageSentRef = useRef(false);
+ const hasInitializedChatRef = useRef(false);
// Model override state (temporary, not saved to agent config)
const [modelOverride, setModelOverride] = useState<string | null>(null);
@@ -38,8 +45,10 @@ export const ChatContextProvider: FC<IProps> = ({ children }) => {
});
const { data: settingsData, isLoading: isAgentSettingsLoading } = useAgentSettings(agentId);
+ const { mutateAsync: createChat, isPending: isChatCreating } = useCreateChatMutation();
+ const { mutateAsync: updateAgentSettings } = useUpdateAgentSettingsMutation();
+
const agentSettings = settingsData?.settings;
- const agentLoading = isAgentLoading || isAgentSettingsLoading;
// ============================================================================
// FILE UPLOAD MANAGEMENT
@@ -56,7 +65,7 @@ export const ChatContextProvider: FC<IProps> = ({ children }) => {
isStreaming,
isProcessing,
- sendMessage,
+ sendMessage: sendChatMessage,
retryMessage,
clearMessages,
stopGenerating,
@@ -72,20 +81,126 @@ export const ChatContextProvider: FC<IProps> = ({ children }) => {
onError: (err) => console.error('Chat error:', err), // eslint-disable-line no-console
});
+ // ============================================================================
+ // CHAT ACTIONS
+ // ============================================================================
+
+ /**
+ * Sends a message with optional file attachments
+ * Integrates with the file upload system
+ */
+ const sendMessage = useCallback(
+ async (message: string) => {
+ if (!message.trim() && files.data.length === 0) return;
+
+ try {
+ // Send message with already-uploaded files
+ const filesForChat =
+ files.data.length > 0
+ ? (files.data as unknown as Parameters<typeof sendChatMessage>[1])
+ : undefined;
+ await sendChatMessage(message, filesForChat);
+
+ // Clear files after successful send
+ files.clearFiles();
+ } catch (error) {
+ console.error('Failed to send message:', error); // eslint-disable-line no-console
+ }
+ },
+ [files, sendChatMessage],
+ );
+
+ /**
+ * Creates a new chat session/conversation
+ */
+ const createSession = useCallback(async () => {
+ try {
+ const conversation = await createChat({
+ conversation: {
+ summary: '',
+ chunkSize: 100,
+ lastChunkID: '0',
+ label: 'New Chat',
+ aiAgentId: agentId,
+ },
+ });
+
+ await updateAgentSettings({
+ agentId,
+ settings: { key: 'lastConversationId', value: conversation?.id },
+ });
+ } catch (error) {
+ console.error('Error creating chat session', error); // eslint-disable-line no-console
+ }
+ }, [agentId, createChat, updateAgentSettings]);
+
+ /**
+ * Clears current chat session and creates a new one
+ */
+ const resetSession = useCallback(async () => {
+ stopGenerating();
+ isFirstMessageSentRef.current = false;
+ clearMessages();
+ files.clearFiles();
+ await createSession();
+
+ // Trigger callback
+ inputRef?.current?.focus();
+
+ // Track observability events
+ Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);
+ Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);
+ }, [createSession, clearMessages, files, stopGenerating, inputRef]);
+
+ // ============================================================================
+ // LIFECYCLE EFFECTS
+ // ============================================================================
+
+ /**
+ * Initialize chat session on component mount
+ * Only runs once when both agent and settings are loaded
+ */
+ useEffect(() => {
+ if (agentSettings && agent && !hasInitializedChatRef.current) {
+ agent.aiAgentSettings = agentSettings;
+ agent.id = agentId;
+
+ // This ensures fresh conversation every time user loads the page
+ hasInitializedChatRef.current = true;
+ createSession().then(() => inputRef?.current?.focus());
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [agentSettings, agent, agentId]); // Only depend on core values, not callbacks
+
+ /**
+ * Track chat session lifecycle for observability
+ */
+ useEffect(() => {
+ Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_START);
+ return () => Observability.observeInteraction(EVENTS.CHAT_EVENTS.SESSION_END);
+ }, []);
+
// Memoize the store to avoid unnecessary re-renders
const values: IChatContext = useMemo(
() => ({
ref: { input: inputRef, container: containerRef },
- agent: { data: agent, settings: agentSettings, loading: agentLoading },
+ agent: {
+ data: agent,
+ settings: agentSettings,
+ isLoading: { agent: isAgentLoading, settings: isAgentSettingsLoading },
+ },
files,
chat: {
+ isChatCreating,
messages,
isStreaming,
isProcessing,
+ createSession,
sendMessage,
retryMessage,
stopGenerating,
clearMessages,
+ resetSession,
},
modelOverride,
@@ -96,15 +211,21 @@ export const ChatContextProvider: FC<IProps> = ({ children }) => {
containerRef,
agent,
agentSettings,
- agentLoading,
+ isAgentLoading,
+ isAgentSettingsLoading,
files,
+
+ isChatCreating,
messages,
isStreaming,
isProcessing,
+ createSession,
sendMessage,
retryMessage,
stopGenerating,
clearMessages,
+ resetSession,
+
modelOverride,
setModelOverride,
],
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 5490fa5e..f7f572ae 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,6 @@
export * from './agent-settings';
export * from './use-agent-chat-context';
+export * from './use-attachments';
export * from './use-chat';
export * from './use-chat-stream';
export * from './use-clipboard-paste';
@@ -7,3 +8,4 @@ export * from './use-create-chat';
export * from './use-drag-and-drop';
export * from './use-fileupload';
export * from './use-scroll-to-bottom';
+export * from './use-store';
diff --git a/packages/app/src/react/features/ai-chat/hooks/use-store.tsx b/packages/app/src/react/features/ai-chat/hooks/use-store.tsx
index c6026217..6a781fdf 100644
--- a/packages/app/src/react/features/ai-chat/hooks/use-store.tsx
+++ b/packages/app/src/react/features/ai-chat/hooks/use-store.tsx
@@ -1,9 +1,9 @@
import { ChatContext, IChatContext } from '@react/features/ai-chat/contexts/chat-context';
import { useContext } from 'react';
-export const useChatContext = () => useContext(ChatContext);
+export const useChatStores = () => useContext(ChatContext);
-export const useChatContextValue = <T extends keyof IChatContext>(state: T): IChatContext[T] => {
+export const useChatStore = <T extends keyof IChatContext>(state: T): IChatContext[T] => {
const store = useContext(ChatContext);
if (!store) throw new Error('ChatContext not found');
return store[state];